如何显示上级类别中的相关帖子

时间:2017-02-24 作者:stack kid

我使用以下代码显示相关帖子,但它只显示该类别的帖子,就像品牌只显示品牌帖子一样。我要找的是,如果我在child下选择任何帖子(品牌、广告、在线等),它应该显示营销下的所有帖子,这样我就不必为帖子分配多个类别

主题营销(3)品牌(1)广告(1)在线(1)

<?php

$related = get_posts( array( \'category__in\' => wp_get_post_categories($post->ID), \'numberposts\' => 5, \'post__not_in\' => array($post->ID) ) );
if( $related ) foreach( $related as $post ) {
setup_postdata($post); ?>
<ul> 
    <li>
    <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
        <?php the_content(\'Read the rest of this entry &raquo;\'); ?>
    </li>
</ul>   

<?php } wp_reset_postdata(); ?>

1 个回复
SO网友:Sonali

只需更改这一行:

   $cat_obj = $wp_query->get_queried_object();
    $thiscat_id = $cat_obj->term_id;
    $thiscat = get_category($thiscat_id);
    $chi = array();
    if (!empty($thiscat->parent)) {
        $parentcat = get_category($thiscat->parent);
        $categories_chi=get_categories(
            array( \'parent\' => $parentcat->cat_ID )
        );

        foreach ($categories_chi as $key => $value) {
            $chi[] = $value->cat_ID;
        }
        $pare = array($parentcat->term_id);
        $ids = array_merge($pare, $chi);
    } else {
        $ids = array($cat_obj->term_id);
    }

    $related  = get_posts(array( \'category__in\' => $ids, \'numberposts\' => 10));

相关推荐

如何将Java脚本添加到Custom-Page.php模板?

如何将javascript添加到自定义页面。php模板?如何使从w3schools ajax教程获得的以下javascript在自定义页面上工作。php模板?任何帮助都将不胜感激。工作javascript包含在以下HTML中:<!DOCTYPE html> <html> <style> table,th,td { border : 1px solid black; border-collapse: collapse;&#x