Search code examples
phpwordpresswoocommercesidebarcustom-taxonomy

Remove sidebar from product categories which display type is subcategories in Woocommerce


I'd like to write a function that removes the sidebar from any product category page in woocommerce whose display type is subcategories.

Some kind of function that says if this category has display type subcategories then disappear the sidebar.

Any help is appreciated.


Solution

  • It mainly depend on your theme own customizations. So the following code will only handle:

    • The default woocommerce behavior based on woocommerce_sidebar action hook.
    • The storefront theme based on storefront_sidebar action hook.

    The custom conditional function:

    First, here below is a custom conditional function that will check if a product category term is set with 'subcategories' display type:

    // Custom conditional function that check for "subcategories" display type in product categories term
    function is_subcategory_display_type( $term ) {
        $taxonomy = 'product_cat';
    
        if( ! term_exists( $term, $taxonomy ) )
            return false;
    
        if( ! is_numeric( $term ) )
            $term = get_term_by( 'slug', sanitize_title( $term ), $taxonomy )->term_id;
    
        return get_term_meta( $term, 'display_type', true ) === 'subcategories' ?  true : false;
    }
    

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


    Then you will add one of those depending on your theme:

    1) For normal themes using the default woocommerce_sidebar hook:

    // Removing default themes woocommerce sidebar conditionally
    add_action( 'woocommerce_sidebar', 'remove_woocommerce_sidebar', 1, 1 );
    function remove_woocommerce_sidebar( $name ){
    
        $queried_object_id = get_queried_object_id();
    
        if ( is_product_category() && is_subcategory_display_type( $queried_object_id ) ){
            remove_action('woocommerce_sidebar','woocommerce_get_sidebar', 10 );
        }
    }
    

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


    2) For Storefront theme using it's own storefront_sidebar hook:

    // Removing default "Storefront" theme woocommerce sidebar conditionally
    add_action( 'storefront_sidebar', 'remove_storefront_get_sidebar', 1, 1 );
    function remove_storefront_get_sidebar( $name ){
    
        $queried_object_id = get_queried_object_id();
    
        if ( is_product_category() && is_subcategory_display_type( $queried_object_id ) ){
            remove_action('storefront_sidebar','storefront_get_sidebar', 10 );
        }
    }
    

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


    3) Other themes with specific customizations:

    You will have to find out which hook is used to make the code work.