$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>How to change WP Query to display related posts|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

How to change WP Query to display related posts

matteradmin12PV0评论

I am creating a WP block theme and want to show related posts on the single post page. Using the Query Loop block, I have added a new pattern that displays the latest posts. Now I want to change the query loop to display related posts in this pattern. I wrote the code and it works but when I add another Query Loop block (latest posts) to that page it shows the related posts. How do I change the code to only display related posts in the selected pattern?

Code in my pattern:

    <!-- wp:query {"query":{"blockName":"related-posts","perPage":3,"pages":0,"offset":0,"postType":"post","order":"desc","orderBy":"date","author":"","search":"","exclude":[],"sticky":"","inherit":false},"enhancedPagination":true,"align":"wide"} -->
    <div class="wp-block-query alignwide">
        <!-- wp:post-template {"layout":{"type":"grid","columnCount":null,"minimumColumnWidth":"22rem"}} -->
            <!-- wp:post-featured-image {"isLink":true,"aspectRatio":"4/3","style":{"spacing":{"margin":{"bottom":"1.25rem"}}}} /-->

            <!-- wp:group {"style":{"spacing":{"margin":{"bottom":"0.5rem"},"blockGap":"0.75rem"}},"layout":{"type":"flex","flexWrap":"nowrap"}} -->
            <div class="wp-block-group" style="margin-bottom:0.5rem">
                <!-- wp:post-terms {"term":"category"} /-->
                <!-- wp:post-date {"format":"F j, Y","isLink":true} /-->
            </div>
            <!-- /wp:group -->

            <!-- wp:post-title {"isLink":true,"style":{"spacing":{"margin":{"top":"0","bottom":"0"}}},"fontSize":"medium"} /-->
        <!-- /wp:post-template -->
    </div>
    <!-- /wp:query -->

Cade in my functions.php:

if ( ! function_exists( 'theme_related_posts' ) ) :
    /**
     * Filtering the query to display related posts.
     *
     * @since Theme 1.0.0
     *
     * @return $pre_render
     */
    function theme_related_posts( $pre_render, $block ) {
        if ( ! is_singular( 'post' ) || is_attachment() ) {
            return $pre_render;
        }

        if (
            isset( $block[ 'attrs' ][ 'query' ][ 'blockName' ] )
            && 'related-posts' === $block[ 'attrs' ][ 'query' ][ 'blockName' ]
        ) {
            add_filter( 'query_loop_block_query_vars', function( $query ) use ( $block ) {
                $current_post_id = get_the_ID();
                $categories = wp_get_post_categories( $current_post_id );

                if ( ! empty( $categories ) ) {
                    $query['category__in'] = $categories;
                }

                $query[ 'post__not_in' ] = array( $current_post_id );

                return $query;
            } );
        }

        return $pre_render;
    }

endif;
add_filter( 'pre_render_block', 'theme_related_posts', 10, 2 );

I am creating a WP block theme and want to show related posts on the single post page. Using the Query Loop block, I have added a new pattern that displays the latest posts. Now I want to change the query loop to display related posts in this pattern. I wrote the code and it works but when I add another Query Loop block (latest posts) to that page it shows the related posts. How do I change the code to only display related posts in the selected pattern?

Code in my pattern:

    <!-- wp:query {"query":{"blockName":"related-posts","perPage":3,"pages":0,"offset":0,"postType":"post","order":"desc","orderBy":"date","author":"","search":"","exclude":[],"sticky":"","inherit":false},"enhancedPagination":true,"align":"wide"} -->
    <div class="wp-block-query alignwide">
        <!-- wp:post-template {"layout":{"type":"grid","columnCount":null,"minimumColumnWidth":"22rem"}} -->
            <!-- wp:post-featured-image {"isLink":true,"aspectRatio":"4/3","style":{"spacing":{"margin":{"bottom":"1.25rem"}}}} /-->

            <!-- wp:group {"style":{"spacing":{"margin":{"bottom":"0.5rem"},"blockGap":"0.75rem"}},"layout":{"type":"flex","flexWrap":"nowrap"}} -->
            <div class="wp-block-group" style="margin-bottom:0.5rem">
                <!-- wp:post-terms {"term":"category"} /-->
                <!-- wp:post-date {"format":"F j, Y","isLink":true} /-->
            </div>
            <!-- /wp:group -->

            <!-- wp:post-title {"isLink":true,"style":{"spacing":{"margin":{"top":"0","bottom":"0"}}},"fontSize":"medium"} /-->
        <!-- /wp:post-template -->
    </div>
    <!-- /wp:query -->

Cade in my functions.php:

if ( ! function_exists( 'theme_related_posts' ) ) :
    /**
     * Filtering the query to display related posts.
     *
     * @since Theme 1.0.0
     *
     * @return $pre_render
     */
    function theme_related_posts( $pre_render, $block ) {
        if ( ! is_singular( 'post' ) || is_attachment() ) {
            return $pre_render;
        }

        if (
            isset( $block[ 'attrs' ][ 'query' ][ 'blockName' ] )
            && 'related-posts' === $block[ 'attrs' ][ 'query' ][ 'blockName' ]
        ) {
            add_filter( 'query_loop_block_query_vars', function( $query ) use ( $block ) {
                $current_post_id = get_the_ID();
                $categories = wp_get_post_categories( $current_post_id );

                if ( ! empty( $categories ) ) {
                    $query['category__in'] = $categories;
                }

                $query[ 'post__not_in' ] = array( $current_post_id );

                return $query;
            } );
        }

        return $pre_render;
    }

endif;
add_filter( 'pre_render_block', 'theme_related_posts', 10, 2 );
Share Improve this question asked Apr 21 at 7:22 Uladzimir KuleshUladzimir Kulesh 234 bronze badges 3
  • Maybe because the query_loop_block_query_vars filter you add gets applied globally to all Query Loop blocks rendered after your related-posts block. Have you tried to remove the filter right after applying it? – Narek Zakarian Commented Apr 21 at 7:48
  • I don't know how to do this, can you hepl me with this? And do you know how to apply a filter to my query instead of globally? – Uladzimir Kulesh Commented Apr 21 at 8:17
  • note that post__not_in carries a big performance cost, it's very slow and expensive to do, it's much cheaper and faster to ask for all the posts and then remove the post you don't want in PHP – Tom J Nowell Commented Apr 21 at 13:18
Add a comment  | 

3 Answers 3

Reset to default 2

I wrote the code and it works but when I add another Query Loop block (latest posts) to that page it shows the related posts.

That happens because although your filter callback is registered only when blockName is related-posts, the query_loop_block_query_vars hook still applies globally to all Query Loop blocks rendered after that.

How do I change the code to only display related posts in the selected pattern?

If you ever do need to use pre_render_block to register your callback:

  • You can use a variable to ensure your callback is only modifying the query once (e.g. using a static flag).

  • You can unhook your callback after it's called once using a named function and remove_filter().

You can see working examples here.

The Better Way

As stated in @birgire's answer, your callback can accept the second parameter of query_loop_block_query_vars, which includes the block’s context — containing the original attributes from your block/pattern markup.

  • With this approach, there's no need to use the pre_render_block filter — you can apply your custom logic directly.
add_filter( 'query_loop_block_query_vars', 'filter_query_loop_block_query_vars', 10, 2 );
function filter_query_loop_block_query_vars( $query, \WP_Block $block ) {
    $block_context_query = $block->context['query'];
    if ( isset( $block_context_query['blockName'] ) &&
        'related-posts' === $block_context_query['blockName']
    ) {
        // Add your custom logic here.
    }

    return $query;
}

This method is more robust because it relies on actual block context rather than when the block is rendered, reducing the risk of affecting other Query Loop blocks unintentionally.

The actual code I used (for testing):

add_filter( 'query_loop_block_query_vars', 'filter_query_loop_block_query_vars', 10, 2 );
function filter_query_loop_block_query_vars( $query, \WP_Block $block ) {
    $block_context_query = $block->context['query'];
    if ( isset( $block_context_query['blockName'] ) &&
        'related-posts' === $block_context_query['blockName']
    ) {
        $current_post_id = get_the_ID();
        $post_categories = get_the_category( $current_post_id );

        if ( ! empty( $post_categories ) ) {
            $query['category__in'] = wp_list_pluck( $post_categories, 'term_id' );

            // Use post__not_in sparingly, especially with large sets of post IDs,
            // as it can negatively impact query performance.
            $query['post__not_in'] = array( $current_post_id );
        }
    }

    return $query;
}
  • I used get_the_category() instead of wp_get_post_categories() because the latter doesn’t use caching and will trigger a database query each time it's called.

  • get_the_category() returns an array of full category objects, so I used wp_list_pluck() to extract just the term IDs needed for the query.

  • This small optimization avoids unnecessary queries and keeps things efficient.

Here are three different approaches and each one only uses a single filter to target the custom block attribute to modify the arguments of WP_Query in the block:

Query Block

We should be able to add an unregistered custom showRelatedPostsWPSE attribute in the pattern, like:

<!-- wp:query { "query":{ "showRelatedPostsWPSE":true, … } } -->

and then target it in PHP with a filter:

add_filter( 'query_loop_block_query_vars', function( array $query, \WP_Block $block ) : array {
    if ( ( $block->block_type->ancestor[0] ?? null ) !== 'core/query' ) {
        return $query;
    }
    if ( ! ( $block->context['query']['showRelatedPostsWPSE'] ?? false ) ) {
        return $query;
    }
    // your custom logic here containing $query['category__in'] = ...
    return $query;
}, 10, 2 );

This filter is applied within the core/post-template block where WP_Query is placed.

Therefore we use the block context of the parent block here.

This should also work similarly if we register variations of the Query Block with the custom attribute.

If we want to do some further work with the custom attribute in the Query Block's UI, we might consider registering it formally. For example by modifying the block's registration via addFilter in JS.

Template Block

We might also add this to the core/post-template block:

<!-- wp:post-template { "showRelatedPostsWPSE":true, "layout": {…} } -->

and then target it in PHP with a filter:

add_filter( 'query_loop_block_query_vars', function( array $query, \WP_Block $block ) : array {
    if ( $block->name !== 'core/post-template') {
        return $query;
    }
    if ( ! ( $block->attributes['showRelatedPostsWPSE'] ?? false ) ) {
        return $query;
    }
    // your custom logic here containing $query['category__in'] = ...
    return $query;
}, 10, 2 );

accessing the attributes of the current template block.

Filtering block attributes

For the custom attribute to be outside of the query attribute:

<!-- wp:query { "showRelatedPostsWPSE": true, "query":{ … } } -->

we could consider the following filtering on the parsed block attributes of the Query Block:

add_filter( 'render_block_data', function( array $parsed_block ) : array {
    if ( $parsed_block['blockName'] !== 'core/query') {
        return $parsed_block;
    }
    if ( ! ( $parsed_block['attrs']['showRelatedPostsWPSE'] ?? false ) ) {
        return $parsed_block;
    }
    // your logic here containing $parsed_block['attrs']['query']['category__in'] = ...
    return $parsed_block;
} );

Hopefully you can adjust this further to your needs.

You can wrap the add_filter in a temporary callback and remove the filter immediately after the block is rendered.

function theme_related_posts( $pre_render, $block ) {
if ( ! is_singular( 'post' ) || is_attachment() ) {
    return $pre_render;
}

if (
    isset( $block['attrs']['query']['blockName'] ) &&
    'related-posts' === $block['attrs']['query']['blockName']
) {
    // Define a unique temporary filter
    $callback = function( $query ) {
        $current_post_id = get_the_ID();
        $categories = wp_get_post_categories( $current_post_id );

        if ( ! empty( $categories ) ) {
            $query['category__in'] = $categories;
        }

        $query['post__not_in'] = array( $current_post_id );

        return $query;
    };

    // Add the filter
    add_filter( 'query_loop_block_query_vars', $callback );

    // Render the block with the filter applied
    $rendered = render_block( $block );

    // Remove the filter immediately after
    remove_filter( 'query_loop_block_query_vars', $callback );

    return $rendered;
}

return $pre_render;
}
add_filter( 'pre_render_block', 'theme_related_posts', 10, 2 );

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far