【问题标题】:Current cateogry in wordpress category menuwordpress 类别菜单中的当前类别
【发布时间】:2017-02-13 09:55:32
【问题描述】:

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

<?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,如下所示 &lt;a class="blog-panel-cat-menu bg-color-1 blog-cat-focus" href="%1$s" alt="%2$s"&gt;%3$s&lt;/a&gt;

【问题讨论】:

    标签: php wordpress if-statement categories


    【解决方案1】:

    试试这个代码。添加了另外两行来检查当前类别。

    <?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;
          }
      } 
    ?>
    

    【讨论】:

    • 太棒了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多