skip to Main Content

I’m trying to make category page to show 7 columns , but it modifies subcategories too. Is there any way to modify only the main category page without applying it to subcategories?
https://www.prospecs.lt/?post_type=product

my code :

add_filter('loop_shop_columns', 'loop_columns', 999);
if (!function_exists('loop_columns')) {
    function loop_columns() {
        return 7; // 3 products per row
    }
}

3

Answers


  1. You can apply the condition and separated the templates for the category and subcategory page.

    $cat = get_the_terms( $product->ID, 'product_cat' );
    foreach ($cat as $categoria) {
       if($categoria->parent == 0){
         // Use here parent categories template
       }
    }
    
    Login or Signup to reply.
  2. You can check if it the current page is a subcategory with this function.

    function is_subcategory($cat_id = null) {
        if (is_tax('product_cat')) {
    
            if (empty($cat_id)){
                $cat_id = get_queried_object_id();
            }
    
            $cat = get_term(get_queried_object_id(), 'product_cat');
            if ( empty($cat->parent) ){
                return false;
            }else{
                return true;
            }
        }
        return false;
    }
    

    You can then use it in your if statement

    add_filter('loop_shop_columns', 'loop_columns', 999);
    if (!function_exists('loop_columns') && !is_subcategory()) {
        function loop_columns() {
            return 7;
        }
    }
    
    Login or Signup to reply.
  3. Note that in your code, the main filter argument is missing for your function. Now you can use the following to define the main product category loop columns:

    add_filter('loop_shop_columns', 'main_product_category_loop_columns', 999);
    function main_product_category_loop_columns( $columns ) {
        if( ! is_product_category() )
            return $columns;
    
        $term = get_queried_object();
    
        if( $term && is_a($term, 'WP_Term') ) {
            return $term->parent > 0 ? $columns : 7;
        }
        return $columns;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search