繁体   English   中英

从相关职位中排除特定类别的职位

[英]Exclude specific category posts from being showed in related posts

我正在使用此代码从帖子的第一类别中选择相关的帖子,但是如果其中一个类别显示为第一,则我需要排除/跳过多个类别中的一个。

<?php 
    // the query
    global $post;
    // We should get the first category of the post
    $categories = get_the_category( $post->ID );
    $first_cat = $categories[0]->cat_ID;
    $the_query = new WP_Query(  $args = array(
            // It should be in the first category of our post:
            'category__in' => array( $first_cat ),
            // Our post should NOT be in the list:
            'post__not_in' => array( $post->ID ),
            // ...And it should fetch 9 posts
            'posts_per_page' => 9,
            'orderby' => 'desc'
        )); ?>
    <?php if ( $the_query->have_posts() ) : ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

我怎样才能做到这一点?

如果您要查找“相关”帖子,除非相关类别为81,则可以执行以下操作:

$categories_to_exclude [ 81, 11, 21 ];
$first_cat  = false; 
$categories = get_the_category( $post->ID );
while ( ! empty( $categories ) && false === $first_cat ) {
   if ( in_array($categories[0]->cat_ID, $categories_to_exclude) ) {
      array_shift($categories);
   }
   else {
       $first_cat = $categories[0]->cat_ID;
   }
}

您可以使用get_the_category获得类别。 然后在while循环中,如果第一个类别为81,则跳过该类别,然后再次查看。 如果不是81(并且仍然有可用的类别),请将其分配给$first_cat并继续。

然后,如果$first_cat不为false ,则仅执行“相关”查询。

注释使您感到困惑,但是如果您想从搜索中排除一个或多个类别中的帖子,则必须使用category__not_in ,它确实接受数组。 因此,您可以执行以下操作:

'category__not_in' => [44, 71, 85],

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM