Reputation: 817
I am using a wordpress registered menu to display an unordered list of product tags on my product archives page.
I would like to maintain the hierarchy of an unordered list if possible, however, I would like to grey out the list items that have no products associated with them so users are not led to a page with no products.
the unordered list looks like this after wordpress does its thing, so each anchor has a title that is equal to the tag name:
<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>
I used a filter to change the href of each anchor to be appropriate. This is the filter I used in order to change this specific menu's anchor links:
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);
I have gotten a list of all the relevant tags to print out by using:
function woocommerce_product_loop_tags() {
global $post, $product;
echo $product->get_tags();
}
Now let's say for example, this above function only echo's space. Is there a way to filter the menu further to hide all the menu items that do not equal space?
I'm thinking it would be something like this:
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.
}
}
}
}
Upvotes: 0
Views: 466
Reputation: 3374
$product->get_tags()
returns an array of tags. You can use PHP in_array()
function to check if your title is on the list:
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.
}
}
}
}
Upvotes: 1