Site logo

Archived topic

Query Loop to display Both Pages and Posts

5 replies · Started by Ian on November 4, 2022

Viewing posts 1–6 of 6

We have a site where content was created in a post AND pages. I can use a category or tag to filter the content but I noticed Query Loop does not have a way to display both posts and pages in the same loop? Is there a way to accomplish this if I can tag each post + page with a specific Category?

Hi Ian,

Add a class to the Grid block nested in the query loop block, eg. my-class-name, then add this snippet:

add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
    if ( ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'my-class-name' ) !== false ) {
        $query_args['post_type'] = array('page', 'post');
    }

    return $query_args;
}, 10, 2 );

Thank you Ying! I can see both Pages and Posts in the loops result now. I am not able to sort by the ACF custom field title. Would you mind taking a look? Login info provided.

Hi there,

orderby custom fields is not something the REST API supports, so until we build our own function into GB Pro it too requires a filter. But you can combine it with Yings args filter into one snipept:


add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
    // Check your logic to apply the filtering only to specific loop
    if (
        ! empty( $attributes['className'] ) &&
        strpos( $attributes['className'], 'my-class-name' ) !== false
    ) {
    // Merge the current $query_args which contains arguments defined in the editor with your ordering arguments
    return array_merge( $query_args, array(
        'post_type' => array('page', 'post'),
        'meta_key' => 'your_custom_field_key',
        'orderby' => 'meta_value_num',
        'order' => 'desc',
    ) );
    }

    return $query_args;
}, 10, 2 );

Thank you Ying and David! I tweaked orderby and this seem to work:

/** query loop to display pages and posts */
add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
    // Check your logic to apply the filtering only to specific loop
    if (
        ! empty( $attributes['className'] ) &&
        strpos( $attributes['className'], 'my-class-name' ) !== false
    ) {
    // Merge the current $query_args which contains arguments defined in the editor with your ordering arguments
    return array_merge( $query_args, array(
        'post_type' => array('page', 'post'),
        'meta_key' => 'country_name',
        'orderby' => 'country_name',
        'order' => 'asc',
    ) );
    }

    return $query_args;
}, 10, 2 );

Glad to hear that. And thanks for sharing your final code!

This archived topic is closed to new replies.