返回类别和说明列表并设置当前页面项

时间:2013-10-21 17:45:11

标签: php wordpress wordpress-theming

我需要返回所有类别的列表和类别描述以构建子导航。我的下面的代码执行此操作,但我希望能够通过在li元素上添加一个类来突出显示当前类别。我怎么能这样做?

<ul class="category-list">
        <?php
        $categories = get_categories('exclude=9&title_li=');
        foreach ($categories as $cat) {
                echo "<li><a href=\"".$cat->category_nicename."\">".$cat->cat_name."<p>".$cat->category_description."</p></a></li>";
        }
        ?>
</ul>

2 个答案:

答案 0 :(得分:0)

如果$ name是您要突出显示的名称,

<?php 
$name = get_query_vars('category');  //applying what the other answer used
?>

<ul class="category-list">
<?php
    $categories = get_categories('exclude=9&title_li=');
    foreach ($categories as $cat) {
        if($cat->cat_name == $name) {  //this might have to be $cat->category_nicename
            echo "<li class=\"highlighted\">";
        } else {
            echo "<li>";
        }
        echo "<a href=\"".$cat->category_nicename."\">".$cat->cat_name <p>".$cat->category_description."</p></a></li>";
    }
    ?>
</ul>

答案 1 :(得分:0)

在wordpress中,您可以注册相同的菜单,然后将所有类别和子类别添加到列表中,

http://codex.wordpress.org/Function_Reference/register_nav_menus

这样,默认情况下,所有当前的班级和其他导航都可用。

如果你不想那么多,可以使用url中的查询类别,然后检查并突出显示相同的内容。

   $current_cat = get_query_vars('category'); //please confirm if its category or cat

然后在你的循环中,检查

   foreach ($categories as $cat) { 
       $class = ( $cat->slug == $current_cat ) ? 'current-item' : ''; ?>
       <li class="<?php echo $class; ?>" > 
         <a href="<?php get_category_link( $cat->term_id ); ?>">
            <?php echo $cat->name; ?>
            <p>".$cat->description."</p>
         </a>
       </li><?php
   }
相关问题