Search code examples
wordpresswoocommercecategories

Woocommerce subcategories dissappear when changing page


When the URL of the products page is /?product_cat=tricka&paged=1 the subcategories are shown. When i change the page to /?product_cat=tricka&paged=2 the subcategories disappier.

I'm getting the subcategories like that:

<?php 
$subcategories = woocommerce_maybe_show_product_subcategories();
if ( $subcategories ) {
    echo '<div class="products subcategories row custom-category-align-and-border">', $subcategories, '</div>';
}

What could be the issue here?

Couldn't find solution anywhere..


Solution

  • You can check whether the variable returns empty and generate the required HTML code yourself.

    <?php 
    $subcategories = woocommerce_maybe_show_product_subcategories();
    if ( $subcategories ) {
        echo '<div class="products subcategories row custom-category-align-and-border">', $subcategories, '</div>';
    }
    else{
        $category = get_queried_object();
        $category_id = $category->term_id;
        custom_show_subcategories_with_images_atakanau($category_id);
    }
    function custom_show_subcategories_with_images_atakanau($parent_category_id) {
        $args = array(
            'taxonomy' => 'product_cat',
            'parent' => $parent_category_id
        );
        $subcategories = get_terms($args);
        
        if ($subcategories) {
            $output = '<ul class="subcategories">';
    
            foreach ($subcategories as $subcategory) {
                $category_image = get_term_meta($subcategory->term_id, 'thumbnail_id', true);
                if (empty($category_image)) {
                    $image_url = wc_placeholder_img_src();
                }
                else{
                    $image_url = wp_get_attachment_url($category_image);
                }
    
                $output .= '<li>';
                $output .= '<a href="' . get_category_link($subcategory->term_id) . '">';
                $output .= '<img src="' . $image_url . '" alt="' . $subcategory->name . '" />';
                $output .= '<span>' . $subcategory->name . '</span>';
                $output .= '</a>';
                $output .= '</li>';
            }
            $output .= '</ul>';
            echo $output;
        }
    }