How do I remove Woocommerce sidebar from cart, checkout and single product pages?

Oliver Martin picture Oliver Martin · Sep 6, 2014 · Viewed 17k times · Source

Like many people that start using woocommerce for the first time I need to know how to customise it. In my particular situation I want to remove the sidebar from the Cart, Checkout and single product pages. My sidebar is defined and called from sidebar.php using the code below:

<?php dynamic_sidebar('global-sidebar'); ?>

I have tried for a long time to find an answer that works but I can't seem to find the correct code or solution. Perhaps asking the question myself will work. By the way I really appreciate the answers in the other articles and how-to's but they don't work for me.

Before I go any further I am using Bootstrap (latest version as of 2014) to style my Wordpress website. Not sure if that matters but maybe it does somehow.

Can someone please tell me how I find and then tell Woocommerce not to display any kind of sidebar on the Cart, Checkout and Single Product pages?

p.s. The website can be found here > wp.wunderful.co.uk (staging site for a client website project)

Answer

helgatheviking picture helgatheviking · Sep 7, 2014

In theory, something like the following ought to work, but I haven't tested it. (To be added to your theme's functions.php)

function so_25700650_remove_sidebar(){
    if( is_checkout() || is_cart() || is_product() ){
        remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );
    }
}
add_action('woocommerce_before_main_content', 'so_25700650_remove_sidebar' );

If you look at the Woo templates you will see

<?php
    /**
     * woocommerce_sidebar hook
     *
     * @hooked woocommerce_get_sidebar - 10
     */
    do_action( 'woocommerce_sidebar' );
?>

This is Woo saying: "Display the sidebar here". But it is adding the woocommerce_get_sidebar function to the woocommerce_sidebar hook... which is convenient because it allows you to unhook that function like I've shown above. Finally, I am using Woo's conditional logic to only unhook the function from its action on the pages you requested.

I'm running my function on the woocommerce_before_main_content hook, which I think should work assuming your theme hasn't removed that hook. If so, then you could probably use wp_head or something that is guaranteed to be there, though then you'd probably want to check that the is_checkout(), etc functions exist or risk breaking your theme should you ever deactivate WooCommerce. As I have it, i should only run on WooCommerce-specific pages and so checking if the WooCommerce functions are defined is probably overkill.

Important Note:

This assumes the default theme or a theme that isn't running its own custom sidebar functions. If your theme is doing something else you will need to investigates its particular functions and templates.