Woocommerce使用wp_nav_menu_objects过滤器使用产品标签来隐藏菜单项



我正在使用wordpress注册菜单在我的产品档案页面上显示一个无序的产品标签列表。

如果可能的话,我希望保持无序列表的层次结构,但是,我希望将没有产品关联的列表项变为灰色,这样用户就不会被引导到一个没有产品的页面。

无序列表在wordpress完成它的事情之后看起来像这样,所以每个锚都有一个等于标签名称的标题:

<ul id="menu-themes" class="menu">
    <li>
        <a href='#' title='fantasy'>Fantasy</a>
    </li>
    <li>
        <a href='#' title='science'>Science</a>
        <ul class='sub-menu'>
            <li>
                <a href='#' title='space'>Space</a>
            </li>
        </ul>
    </li>        
</ul>

我使用过滤器将每个锚的href更改为合适的。这是我用来改变这个特定菜单的锚链接的过滤器:

function change_menu( $items, $args ){
    if( $args->theme_location == "themes" ){
        foreach($items as $item){
            global $wp;
            $current_url = home_url(add_query_arg(array(),$wp->request));
            $item->url = $current_url . '/?product_tag=' . $item->title;

        }
    }
  return $items;
}
add_filter('wp_nav_menu_objects', 'change_menu', 10, 2);

我已经得到了所有相关标签的列表要打印出来使用:

function woocommerce_product_loop_tags() {
    global $post, $product;

    echo $product->get_tags();
}

现在让我们举个例子,上面的函数只回显空间。是否有一种方法可以进一步过滤菜单以隐藏所有不等于空间的菜单项?

我想应该是这样的:

function filter_menu_by_tags($items, $args){
    //set scope of $product variable
    global $product;
    //this if statement makes sure only the themes menu is affected.
    if( $args->theme_location == "themes"){
        //loop through each menu item
        foreach($items as $item){
            if($item->title does not match any of the tags in $product->get_tags()){
                //then add a special class to the list item or anchor tag
            }
            else{
                 //do nothing and let it print out normally.
            }
        }
    }
}

$product->get_tags()返回一个标记数组。你可以使用PHP in_array()函数来检查你的标题是否在列表上:

function filter_menu_by_tags($items, $args){
    //set scope of $product variable
    global $product;
    //this if statement makes sure only the themes menu is affected.
    if( $args->theme_location == "themes"){
        //loop through each menu item
        foreach($items as $item){
            if( !in_array($item->title, $product->get_tags()) ){
                // Title is not in_array Tags
                //then add a special class to the list item or anchor tag
            }
            else{
                 // Title is in_array Tags
                 //do nothing and let it print out normally.
            }
        }
    }
}

最新更新