wp query - Exclude current post when getting related post on custom post type and taxonomy

The below will return the other post in the same category but it will also return the current post too. Is there a way t

The below will return the other post in the same category but it will also return the current post too.

Is there a way to exclude the current post from the query?

$args = array(
'post_type'     => 'custom_post_type',
'tax_query'     => array(
    array(
        'taxonomy'  => 'custom_taxo',
        'field'     => 'term_id',
        'terms'      => array(1,2,5),
        'operator'  => 'IN'
    )
)
);

$query = new WP_Query( $args );

The below will return the other post in the same category but it will also return the current post too.

Is there a way to exclude the current post from the query?

$args = array(
'post_type'     => 'custom_post_type',
'tax_query'     => array(
    array(
        'taxonomy'  => 'custom_taxo',
        'field'     => 'term_id',
        'terms'      => array(1,2,5),
        'operator'  => 'IN'
    )
)
);

$query = new WP_Query( $args );
Share Improve this question asked Dec 2, 2015 at 8:07 user742736user742736 1773 silver badges7 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 5

Simply add

'post__not_in' => [get_queried_object_id()],

to your array of query arguments. get_queried_object_id() will return the post ID of the currently viewed single post, and post__not_in will skip the posts whos ID's was passed as an array to the parameter

You can use post__not_in with the get_the_ID of the post in this case your code should be like this :

                $args = array(
                            'post_type'     => 'custom_post_type',
                            'tax_query'     => array(
                                array(
                                    'taxonomy'  => 'custom_taxo',
                                    'field'     => 'term_id',
                                    'terms'      => array(1,2,5),
                                    'operator'  => 'IN'
                                )
                            ),
                        'post__not_in' => array (get_the_ID()), 

                    );

                $query = new WP_Query( $args );

Note: The value has to be an array 'post__not_in' => array (get_the_ID())

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744848776a4597003.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信