繁体   English   中英

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

[英]Exclude specific category from Related Posts

希望从博客页面底部的“相关帖子”源中排除特定类别(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;
   }
}

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

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

// 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();

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

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

暂无
暂无

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

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