【问题标题】:Add a tag class to the current Woocommerce product category in a navigation menu在导航菜单中向当前 Woocommerce 产品类别添加标签类
【发布时间】:2018-08-22 04:02:21
【问题描述】:

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

<?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,如果它们匹配,我想给那个锚标记一个类名'current'。 这样我就可以设置一个锚标记的样式以显示当前选择了哪个类别。

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

$current_page_slug = $post->post_name;

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

【问题讨论】:

    标签: php wordpress woocommerce custom-taxonomy


    【解决方案1】:

    要将“当前”类属性添加到当前产品类别的&lt;a&gt; 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>';
    }
    

    【讨论】:

      【解决方案2】:

      你可以像这样抓取当前页面的 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;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-21
        相关资源
        最近更新 更多