wordpress类别菜单中的当前cateogry

时间:2017-02-13 09:55:32

标签: php wordpress if-statement categories

我有一个小脚本,显示包含帖子的任何类别并显示它们(如一个小菜单)

<?php 
  $categories = get_categories( array(
      'orderby' => 'name',
      'order'   => 'ASC'
  ) );
  echo '<a class="blog-panel-cat-menu bg-color-1" href="' . get_permalink( get_option( 'page_for_posts' ) ) . '">All</a>';
  foreach( $categories as $category ) {
      if ($category->count > 0){
        $category_link = sprintf( 
            '<a class="blog-panel-cat-menu bg-color-1" href="%1$s" alt="%2$s">%3$s</a>',
            esc_url( get_category_link( $category->term_id ) ),
            esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
            esc_html( $category->name )
        );
        echo $category_link;
      }
  } 
?>

点击任何链接时,它会重定向到显示该类别帖子的页面,例如mywebsite/news/category/blog/mywebsite/news/category/news/mywebsite/news是显示所有类别的博客主页)

当我在mywebsite/news/category/blog/时,我希望菜单中的“博客”链接在foreach循环中的当前类之后具有类blog-cat-focus,如<a class="blog-panel-cat-menu bg-color-1 blog-cat-focus" href="%1$s" alt="%2$s">%3$s</a>

1 个答案:

答案 0 :(得分:0)

试试这段代码。添加了两行以检查当前类别。

<?php 
  $categories = get_categories( array(
      'orderby' => 'name',
      'order'   => 'ASC'
  ) );
$category = get_category( get_query_var( 'cat' ) );
  echo $cat_id = $category->cat_ID;
  echo '<a class="blog-panel-cat-menu bg-color-1" href="' . get_permalink( get_option( 'page_for_posts' ) ) . '">All</a>';
  foreach( $categories as $category ) {
      if ($category->count > 0){
          $cust_class = '';
          if($category->term_id==$cat_id){$cust_class = 'blog-cat-focus';}
        $category_link = sprintf( 
            '<a class="blog-panel-cat-menu bg-color-1 %4$s>" href="%1$s" alt="%2$s">%3$s</a>',
            esc_url( get_category_link( $category->term_id ) ),
            esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
            esc_html( $category->name ),
            $cust_class

        );
        echo $category_link;
      }
  } 
?>