function your_theme_enqueue_scripts() { wp_enqueue_script('jquery'); // Add here any other scripts you need to enqueue } add_action('wp_enqueue_scripts', 'your_theme_enqueue_scripts'); function load_filtered_cats() { // Security check if (!check_ajax_referer('load_cats_nonce', 'nonce', false)) { wp_send_json_error('Invalid nonce', 400); } $categoryId = isset($_POST['categoryId']) ? intval($_POST['categoryId']) : 0; $args = [ 'taxonomy' => 'product_cat', 'hide_empty' => false, // Include or exclude parent categories as needed ]; // Apply parent filtering only if a specific category ID is provided if ($categoryId > 0) { $args['parent'] = $categoryId; } else { // Exclude top-level categories if looking for all child categories initially // Remove the 'exclude' line if you also want top-level categories included initially $args['exclude'] = get_terms(['taxonomy' => 'product_cat', 'parent' => 0, 'fields' => 'ids']); } $categories = get_terms($args); $sorted_categories = []; // Sorting and grouping categories foreach ($categories as $category) { $products_in_category = new WP_Query([ 'post_type' => 'product', 'posts_per_page' => -1, 'tax_query' => [[ 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $category->term_id, ]], 'meta_query' => [[ 'key' => '_stock_status', 'value' => 'instock', ]], ]); if ($products_in_category->have_posts()) { $first_letter = strtoupper(substr($category->name, 0, 1)); $sorted_categories[$first_letter][] = $category; } } // Sort categories within each group alphabetically foreach ($sorted_categories as &$categories_group) { usort($categories_group, function($a, $b) { return strcmp($a->name, $b->name); }); } // Sort groups by their starting letter ksort($sorted_categories); // Output the sorted and grouped categories foreach ($sorted_categories as $letter => $categories_group) { echo "
" . count($categories_group) . " marcas