将标签 class 添加到导航菜单中的当前 Woocommerce 产品类别

Add a tag class to the current Woocommerce product category in a navigation menu

我有一个这样打印的产品类别导航菜单

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

现在我想比较它们的 href 属性和当前页面的 slug,如果它们匹配,我想给那个锚标记一个 class 名称 'current'。 这样我就可以设置一个锚标记的样式,以显示现在选择了哪个类别。

我发现我可以像这样抓取当前页面的 slug

$current_page_slug = $post->post_name;

我不知道如何一个一个地抓取 href 属性并与 slug 进行比较。 我能得到什么帮助吗?

您可以像这样抓取当前页面的 slug,

// 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;

使用 get_queried_object() 获取当前页面对象更可靠并且不太可能被修改,除非你使用破坏主查询对象的邪恶 query_posts,但是那么就看你的了。

此外,您可以使用上面的方法

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

要将 "current" class 属性添加到当前产品类别的 <a> html 标签,请尝试以下操作:

// 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>';
}