Created
October 7, 2019 18:07
-
-
Save mingodev/8496f799be421610455f47016c12e81e to your computer and use it in GitHub Desktop.
Add category count to category menu items in Wordpress.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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