Naposledy aktivní 1713290640

Malin's Avatar Malin revidoval tento gist 1713290640. Přejít na revizi

1 file changed, 79 insertions

filtered-cats-QRh.php(vytvořil soubor)

@@ -0,0 +1,79 @@
1 + function your_theme_enqueue_scripts() {
2 + wp_enqueue_script('jquery');
3 + // Add here any other scripts you need to enqueue
4 + }
5 +
6 + add_action('wp_enqueue_scripts', 'your_theme_enqueue_scripts');
7 +
8 + function load_filtered_cats() {
9 + // Security check
10 + if (!check_ajax_referer('load_cats_nonce', 'nonce', false)) {
11 + wp_send_json_error('Invalid nonce', 400);
12 + }
13 +
14 + $categoryId = isset($_POST['categoryId']) ? intval($_POST['categoryId']) : 0;
15 +
16 + $args = [
17 + 'taxonomy' => 'product_cat',
18 + 'hide_empty' => false,
19 + // Include or exclude parent categories as needed
20 + ];
21 +
22 + // Apply parent filtering only if a specific category ID is provided
23 + if ($categoryId > 0) {
24 + $args['parent'] = $categoryId;
25 + } else {
26 + // Exclude top-level categories if looking for all child categories initially
27 + // Remove the 'exclude' line if you also want top-level categories included initially
28 + $args['exclude'] = get_terms(['taxonomy' => 'product_cat', 'parent' => 0, 'fields' => 'ids']);
29 + }
30 +
31 + $categories = get_terms($args);
32 + $sorted_categories = [];
33 +
34 + // Sorting and grouping categories
35 + foreach ($categories as $category) {
36 + $products_in_category = new WP_Query([
37 + 'post_type' => 'product',
38 + 'posts_per_page' => -1,
39 + 'tax_query' => [[
40 + 'taxonomy' => 'product_cat',
41 + 'field' => 'id',
42 + 'terms' => $category->term_id,
43 + ]],
44 + 'meta_query' => [[
45 + 'key' => '_stock_status',
46 + 'value' => 'instock',
47 + ]],
48 + ]);
49 +
50 + if ($products_in_category->have_posts()) {
51 + $first_letter = strtoupper(substr($category->name, 0, 1));
52 + $sorted_categories[$first_letter][] = $category;
53 + }
54 + }
55 +
56 + // Sort categories within each group alphabetically
57 + foreach ($sorted_categories as &$categories_group) {
58 + usort($categories_group, function($a, $b) {
59 + return strcmp($a->name, $b->name);
60 + });
61 + }
62 +
63 + // Sort groups by their starting letter
64 + ksort($sorted_categories);
65 +
66 + // Output the sorted and grouped categories
67 + foreach ($sorted_categories as $letter => $categories_group) {
68 + echo "<div class='category-group'><h2>" . $letter . "</h2><p class='category-count'>" . count($categories_group) . " marcas</p><hr>";
69 + foreach ($categories_group as $category) {
70 + echo '<a href="' . get_term_link($category) . '" class="category-button">' . esc_html($category->name) . '</a>';
71 + }
72 + echo "</div>"; // Close the category-group div
73 + }
74 +
75 + wp_die(); // Terminate AJAX request correctly
76 + }
77 +
78 + add_action('wp_ajax_load_filtered_cats', 'load_filtered_cats');
79 + add_action('wp_ajax_nopriv_load_filtered_cats', 'load_filtered_cats');
Novější Starší