从“相关帖子”中排除特定类别

时间:2019-06-08 16:36:09

标签: php wordpress categories

试图从博客页面底部的“相关帖子”源中排除特定类别(ID = 100)。如果还可以从侧边栏存档中排除(不确定它们是否已连接?),则可以额外获得奖励

我正在使用WP主题“ TheFox”,问他们-不是主题的一部分。

我“认为”它必须在functions.php中执行。我发现了一些类似的问题和代码,但是没有任何运气。

我是.php的完整菜鸟,所以请保持柔和:)

我发现了其他尝试,没有运气。没有注册或影响Feed。

$categories_to_exclude [ 100 ];
$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;
   }
}

2 个答案:

答案 0 :(得分:0)

从您的问题中可以得出的结论是,您想忽略相关帖子查询中的一个类别(可能更多)?

使用以下代码(注释中的代码给出了一些解释):

// set the category ID (or multiple category IDs) // you want to ignore in the following array $cats_to_ignore = array( 2 ); $categories = wp_get_post_categories( get_the_ID() ); $category_in = array_diff( $categories, $cats_to_ignore ); // ignore only if we have any category left after ignoring if( count( $category_in ) == 0 ) { $category_in = $categories; } $cat_args = array( 'category__in' => $category_in, 'posts_per_page' => 4, 'orderby' => 'date', 'post__not_in' => array( get_the_ID() ) ); $cat_query = new WP_Query( $cat_args ); while ( $cat_query->have_posts() ) : $cat_query->the_post(); /* just example markup for related posts */ echo '<h2><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></h2>'; endwhile; // reset $post after custom loop ends (if you need the main loop after this point) wp_reset_postdata();

答案 1 :(得分:0)

使用下面的代码,它必须可以工作

    $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并继续。