最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - Class active for Archive link - looped out

programmeradmin0浏览0评论

I want to have the current Archive page link to have the class "selected". So if I'm in /category/featured/ that button on the menu should have the class selected. After trying several different ways all im managing to do is make all the archive links have the class if Im in any of those. How can i make it so it only targets one ?

When /category/featured/ is active the rest should not have class selected..

So i have all my categories looped out so:

<?php $categories = get_categories(); ?>

 

<?php  foreach($categories as $category) {
   
   echo '<a class="'. (( is_archive()?'selected"':"")) .'" href="'. get_category_link($category->term_id) . '">' . $category->name . '</a>';
} ?>

I want to have the current Archive page link to have the class "selected". So if I'm in /category/featured/ that button on the menu should have the class selected. After trying several different ways all im managing to do is make all the archive links have the class if Im in any of those. How can i make it so it only targets one ?

When /category/featured/ is active the rest should not have class selected..

So i have all my categories looped out so:

<?php $categories = get_categories(); ?>

 

<?php  foreach($categories as $category) {
   
   echo '<a class="'. (( is_archive()?'selected"':"")) .'" href="'. get_category_link($category->term_id) . '">' . $category->name . '</a>';
} ?>
Share Improve this question asked Mar 1, 2022 at 10:43 KevinKevin 153 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

One way to do this is to get the current object ID with get_queried_object_id() and compare it against the category term ID inside the foreach loop. E.g.

$current_object_id = get_queried_object_id();

foreach (get_categories() as $category) {

  $classes = '';
  if ( $category->term_id === $current_object_id ) {
    $classes .= 'selected';
  }

  printf(
    '<a class="%s" href="%s">%s</a>',
    $classes,
    get_category_link($category->term_id),
    $category->name
  );
}

is_category() should work too as it is basically a fancy wrapper for the same check as above.

foreach (get_categories() as $category) {

  $classes = '';
  // Parameter can be category ID, name, slug, or array of such
  if ( is_category( $category->term_id ) ) {
    $classes .= 'selected';
  }

  printf(
    '<a class="%s" href="%s">%s</a>',
    $classes,
    get_category_link($category->term_id),
    $category->name
  );
}
发布评论

评论列表(0)

  1. 暂无评论