首页 > 解决方案 > Wordpress:如何将活动类添加到附加到帖子的类别中

问题描述

如何将活动类添加到附加到帖子的类别中,这是我的代码

<ul>
    <?php
    $current_id = $wp_query->get_queried_object_id();

    //for each category, show all posts
    $cat_args = array(
        'orderby'  => 'name',
        'order'    => 'ASC',
        'child_of' => 33
    );

    $categories = get_categories($cat_args);

    foreach ($categories as $category) {
        // $current_id = $wp_query->get_queried_object_id(),

        $args = array(
            'showposts'        => -1,
            'category__in'     => array($category->term_id),
            'caller_get_posts' => 1,    
        );

        $posts = get_posts($args);

        if ($posts) {
            //echo '<li'; if ($current_id == $post->ID) echo ' class="current"';  echo '>';

            echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>  ';
            echo '<ul>';
            // echo '<ul'; if ($current_id == $post->ID) echo ' class="current"';  echo '>';
            foreach($posts as $post) {
                setup_postdata($post); ?>
    <li <?php if ($current_id == $post->ID) echo ' class="current"'; ?>><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
    <?php
            } // foreach($posts
            echo '</ul>';
            echo '</li>';
        } // if ($posts
    } // foreach($categories
    wp_reset_postdata();
    ?>
</ul>

这是我的结果:

谁能帮我?谢谢

标签: phpwordpress

解决方案


您需要获取分配给帖子的类别数组。然后,在循环内部,检查每个元素以查看它是否出现在数组中。

代码应该可以工作。

<ul><?php
//
// get IDs of current post categories 
$curr_post_cats = get_the_category();
$cat_ids = wp_list_pluck($curr_post_cats, 'term_id');
//
// [your code...]
//
foreach($categories as $category) {
    //
    // check if "$category" is assigned to current post
    $css_class = '';
    if ( in_array( $category->term_id, $cat_ids )
        $css_class = 'class="current"';

    $args = array(
    //
    // [...]
    //
    $posts = get_posts($args);
    if ($posts) {
        echo "<li {$css_class} >";

        // echo '<a href="' . get_category_link( $category->term_id ) ...
        //
        // rest of your code
        //

推荐阅读