Skip to content

Instantly share code, notes, and snippets.

@mingodev
Created October 7, 2019 18:07
Show Gist options
  • Save mingodev/8496f799be421610455f47016c12e81e to your computer and use it in GitHub Desktop.
Save mingodev/8496f799be421610455f47016c12e81e to your computer and use it in GitHub Desktop.
Add category count to category menu items in Wordpress.
// Short code pour le nombre d'items dans une catégorie
add_shortcode('categoryCount', 'nbProductsCategoryShortcode');
function nbProductsCategoryShortcode ($attributes = []) {
global $wpdb;
$attributes = shortcode_atts([
'category' => null,
], $attributes);
$category = $attributes['category'];
if (empty($category)) return;
$terms = get_terms( 'product_cat' );
$count = 0;
foreach ($terms as $term) {
if ($term->name == $category) $count = $term->count;
}
return '<span class="category-count">('.$count.')</span>';
}
// Ajout du shortcode aux items du menu
add_filter('wp_nav_menu_objects', 'applyCategoryCountToMenu');
function applyCategoryCountToMenu ($items) {
foreach ($items as $key => $menuItem) {
if ($menuItem->type != 'taxonomy') continue;
$menuItem->title = $menuItem->title . ' ' . do_shortcode('[categoryCount category="'.$menuItem->title.'"]');
}
return $items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment