【问题标题】:find top most parent category of post and create active class找到帖子的最顶层父类别并创建活动类
【发布时间】:2019-02-18 18:51:33
【问题描述】:

在我的内容单一页面中,我想在我的类别列表中创建活动课程。我想找到帖子($class)的最高父级。 当我在我的帖子上时,当前最父类别中没有添加活动类(在旁边-> li cat-item)

        <div class="nwa-widget">
            <h2 class="nwa-title">CATEGORIES</h2>
              <ul>
                <?php
                  $exclude_id = get_cat_ID('Non classé');
                  $categories = get_categories( array(
                    'orderby' => 'name',
                    'parent'  => 0,
                    'hide_empty' => 0, // affiche les categories même vides
                    'exclude' => array($exclude_id)  
                  ));

                $category = get_the_category($post->ID);
                $catid = $category[0]->cat_ID;
                $top_level_cat = smart_category_top_parent_id ($catid);

                  foreach ($categories as $cat) :
                   $class = ( cat_is_ancestor_of(  $top_level_cat,  get_the_ID() ) ) ? 'active' : '';

                  the_ID()
                ?>  
                  <li class="cat-item <?php echo $class ?>">                    
                    <a href="<?php echo get_category_link($cat->term_id); ?>"><?php echo $cat->cat_name; ?></a>  
                  </li>
                <?php endforeach; ?>
              </ul> 
        </div>

【问题讨论】:

  • 代码不错,但问题出在哪里。
  • 当我在我的帖子上时,当前最父类别中没有添加活动类(在旁边 -> li cat-item)。

标签: php wordpress


【解决方案1】:

尝试将第一个字符串 $class = ... 替换为 foreach 语句:

$is_active = array_reduce(
    $category,
    function ($carry, $cat) use ($top_level_cat) {
        return $carry || cat_is_ancestor_of($top_level_cat, $cat->cat_ID);
    }
);
$class = is_active? 'active' : '';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 2013-01-24
    • 2019-01-23
    • 2014-08-30
    相关资源
    最近更新 更多