Sorting query loop in Template

  • Hi

    I have below snippet.
    I can’t get it work when I have “Inherit query from template” active.
    Is there a way to get it work?

    **************
    add_filter( ‘generateblocks_query_loop_args’, function( $query_args, $attributes ) {

    if (
    ! is_admin() &&
    ! empty( $attributes[‘className’] ) &&
    strpos( $attributes[‘className’], ‘custom-query-date-order-indhold-1’ ) !== false
    ) {

    $query_args = array_merge( $query_args, array(
    ‘meta_key’ => ‘indhold_dato’,
    ‘orderby’ => ‘meta_value’,
    ‘order’ => ‘DESC’,
    ));
    }
    return $query_args;
    }, 10, 2 );

    Thanks in advance

  • Hi there,

    Yes, when you are using the “Inherit query from template” option, the query pulls the default template; your filter will not affect it anymore.

    Where are you adding the query too? You might want to use WP’s core filter pre_get_posts() to order the default template.

  • I’ve added the filter in a query in an Element Block Loop Template, which is a use for my archives.

  • So yes, you need to change your archives’ default loop using WP’s core filter pre_get_posts().

  • How do I change the snippet – Unfortunately, I’m not particularly strong in that area.

  • Can you link me to the archive so I can write the code for you?

  • Here you are – and thanks?

  • Since you’ve set the loop template’s location to all archives, the code below applies to all archives as well. Try this:

    add_action( 'pre_get_posts', function( $query ) {
    
    	if ( is_admin() || ! $query->is_main_query() ) {
    		return;
    	}
    
    	if ( $query->is_archive() ) {
    
    		$query->set( 'meta_key', 'indhold_dato' );
    		$query->set( 'orderby', 'meta_value' );
    		$query->set( 'order', 'DESC' );
    
    	}
    
    } );
  • It seems to work Ying 🙂

    One silly question.
    When it’s done this way, there is no need for using filter hook?

  • Sorry, what do you mean by “using filter hook”?

  • I mean if I want use more than one loop template located to different archives?
    Hope you understand what I mean…

  • The code is for all archives, so all posts on all archives will be ordered by the code 🙂

  • OK, thanks for the help 🙂

  • You are welcome   🙂

Viewing 14 posts - 1 through 14 (of 14 total)
  • You must be logged in to reply to this topic.