Add product number of a category in the WordPress menu
Publié le 23/01/2023 par Build Your Web
Number of products in a category
When a customer visits your website, you need to be able to give them useful information at first glance. Quand on parle d’un E-Commerce, les prix, les quantités, les nombre de produits ou encore les catégories de produits sont des informations vraiment utiles. They must therefore be quickly visible in the navigation of your website. We will therefore see in this article how to display the number of products in a category and add this information in your WordPress menu.
Overall process of realisation
To achieve this, we will proceed as follows. You need to access the WordPress Menu Filter (the one with the Menu object and not the one with the menu HTML). Next, we will pass each of the items in the Menu object and check if the item is a Product category. Next, we will pass each of the items in the Menu object and check if the item is a Product category. Finally, simply add it to the end of the content of the active element. Complex? No, it’s quite simple, you’ll see!
1 – The WordPress Filter
The filter we will use is: ‘wp_nav_menu_objects’. We will assign a byw_add_product_count_to_menu() function to it which will handle our workflow. 2 parameters are passed in this filter ($items and $args). To learn more about this function, you can see the documentation here.
add_filter( 'wp_nav_menu_objects', 'byw_add_product_count_to_menu', 10, 2 );
function byw_add_product_count_to_menu( $items, $args ) {
return $items;
}
2 – The Audit Function
The first thing is to check whether the menu is the main one. If this is the case, we create a foreach loop on the $items, we check that it is indeed a “Product” category. This is where things get complicated. The menu object does not retrieve the product category id but only the category title (in the Menu) and the category URL (for the link). We will therefore create a function that retrieves the slug from the URL. We check if the URL ends with a ‘/’ (just in case), then we transform the content of the URL into an array. We get the last (or second to last depending on the slash) value of the array and call another function to count. This gives us :
function get_category_slug($url) {
if (str_ends_with($url, '/') ) {
$index = 2;
} else {
$index = 1;
}
$value = explode('/', $url);
return count_products_in_category_by_slug($value[count($value) - $index]);
}
3 – The Counting Function
Now that we have retrieved the category slug, we will use WP_Query to retrieve the number of products attached to this function. This gives us the following function:
function count_products_in_category_by_slug($category_slug) {
$category_id = get_term_by( 'slug', $category_slug, 'product_cat' )->term_id;
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category_id,
),
),
);
$query = new WP_Query( $args );
return $query->found_posts;
}
4 – The Function at the Global
By combining these 3 code blocks, you will have the number of products attached to the categories in your Main Menu. You can also add a check if the number is 0 and not display it. Anyway, here is the full code:
add_filter( 'wp_nav_menu_objects', 'byw_add_product_count_to_menu', 10, 2 );
function byw_add_product_count_to_menu( $items, $args ) {
// Vérification si le menu est bien le principal.
if ( $args->theme_location == 'primary' ) {
// On boucle sur chaque élément du Menu
foreach ( $items as $item ) {
// Vérifie si l'élément de menu est une catégorie produit
if ( $item->object == 'product_cat' ) {
$category_slug = get_category_slug($item->url);
// On compte le nombre de produits dans cette catégorie
//$product_count = wp_count_posts( 'product' )->publish;
// Et on Ajoute le nombre de produits à l'intitulé de l'élément de menu entre deux ()
$item->title .= ' (' . $category_slug. ')';
}
}
}
return $items;
}
function get_category_slug($url) {
if (str_ends_with($url, '/') ) {
$index = 2;
} else {
$index = 1;
}
$value = explode('/', $url);
return count_products_in_category_by_slug($value[count($value) - $index]);
}
function count_products_in_category_by_slug($category_slug) {
$category_id = get_term_by( 'slug', $category_slug, 'product_cat' )->term_id;
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category_id,
),
),
);
$query = new WP_Query( $args );
return $query->found_posts;
}
Visual rendering
And that’s a neat feature. You can of course vary the type of categories to display a counter for your articles for example. In any case, don’t hesitate to post your comments if you have any questions. Otherwise you can also discover our ShortUrl Tracker Plugin (to manage your short links from your website) and of course contact us if you have a Website project!