Custom Query posts from same category terms

I’d like to create a custom PHP query that gets posts that have the same category terms as the current post.

In this code the tax query seems to break the query. It makes it ignore posts_per_page, for example. When I comment out the tax query it shows 4 posts per page as expected.

return [
    'post_type'      => 'post',
    'posts_per_page' => 4,
    'post__not_in'   => [$post->ID],
    'orderby'        => 'rand',
    'order'          => 'DESC',
    'tax_query'      => [
        [
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => wp_get_post_terms($post->ID, 'category', ['fields' => 'ids']),
        ],
    ],
];

Does Bricks require custom formatting?

I think you just have to add global $post to your code, and it should be fine right? at least from what i have tested on the fly (i used post_tag for my test)

global $post // should do the trick

return [
    'post_type'      => 'post',
    'posts_per_page' => 4,
    'post__not_in'   => [$post->ID],
    'orderby'        => 'rand',
    'order'          => 'DESC',
    'tax_query'      => [
        [
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => wp_get_post_terms($post->ID, 'category', ['fields' => 'ids']),
        ],
    ],
];
1 Like

Thank you, SuatB!,That worked!