1
votes

I have a products categories' navigation menu printing out like this

<?php
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
    'orderby'    => $orderby,
    'order'      => $order,
    'hide_empty' => $hide_empty,
            );
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
        echo '<ul>';
    foreach ($product_categories as $key => $category) {
        echo '<li class="menuNav">';
        echo '<a href="/'.$category->slug.'_product_sale/" >';
        echo get_term_meta($category->term_id, 'cat_one', true);
        echo '</a>';
        echo '</li>';
    }
    echo '</ul>';
}
?>

Now I want to compare their href attributes and current page's slug, and if they match, I want to give that anchor tag a class name 'current'. So that I can style that one anchor tag to show which category is selected right now.

I found out I can grab current page's slug like this

$current_page_slug = $post->post_name;

I can't figure out how to grab href attributes one by one and compare with the slug. Could I get any help?

2

2 Answers

2
votes

To add a "current" class attribute to <a> html tag for the current product category, try the following:

// Get the current product category WP_Term
if( is_product_category() ) {
    $queried_obj    = get_queried_object(); 
    $curr_term_slug = $queried_obj->slug; 
} else {
    $curr_term_slug = '';
}

// Get All product categories WP_Term
$product_categories = get_terms( 'product_cat', array(
    'orderby'    => 'name',
    'order'      => 'asc',
    'hide_empty' => false, 
) );

// Product category Navigation
if( ! empty( $product_categories ) ){
        echo '<ul>';
    foreach ( $product_categories as $key => $category ) {

        // CLASS attribute: Comparing the current category to each category
        $class = $category->slug == $curr_term_slug ? 'class="current"' : '';

        echo '<li class="menuNav">';
        echo '<a href="/' . $category->slug . '_product_sale/" ' . $class . '>';
        echo get_term_meta( $category->term_id, 'cat_one', true );
        echo '</a>';
        echo '</li>';
    }
    echo '</ul>';
}
2
votes

You can grab current page's slug like this,

// Get the queried object and sanitize it
$current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );
// Get the page slug
$slug = $current_page->post_name;

Using get_queried_object() to get the current page object is much more reliable and is less likely to be modified, unless you are using the evil query_posts which breaks the main query object, but then that is all up to you.

Also, You can use the above as follow

if ( is_page() )
    $slug = get_queried_object()->post_name;