Home » WooCommerce: Conditionally Hide Widgets

WooCommerce: Conditionally Hide Widgets

by Tutor Aspire

You could use a popular plugin called Widget Logic, or instead you could keep it simple with a few lines of PHP. Here’s a snippet for you in case you need to conditionally hide a certain sidebar widget given a condition e.g. if you’re on the Cart page.

Of course, you can use any of the available WooCommerce conditional tags and make this more complex, but in this example we’ll keep it simple and check if we’re looking at the Cart page (thanks to the is_cart() conditional). Enjoy!

The “woocommerce-products-2” widget ID that I want to hide on the WooCommerce Cart page

PHP Snippet: Remove a Sidebar Widget if @ WooCommerce Cart Page

Note: you’ll need to find the sidebar ID (go to the WordPress dashboard > “Appearance” > “Widgets” and right click on the sidebar in question. Click Inspect on Google Chrome and find the sidebar ID) and the widget ID (see screenshot above for 1 way to do that: right click on the widget, click Inspect on Google Chrome, and find the widget DIV ID).

In regard to my sample snippet below, I found out the sidebar ID is ‘sidebar-1‘ and the widget ID I wanted to hide is ‘woocommerce_products-2‘. You need to make sure you’re targeting the correct sidebar/widget or the code won’t work.

/**
 * @snippet       Hide Sidebar Widget @ WooCommerce Cart
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 3.7
 * @donate $9     https://tutoraspire.com
 */

add_filter( 'sidebars_widgets', 'tutoraspire_woocommerce_conditionally_hide_widget' );

function tutoraspire_woocommerce_conditionally_hide_widget( $sidebars_widgets ) {
    if( ! is_admin() ) {
if ( is_cart() ) {
$key = array_search( 'woocommerce_products-2', $sidebars_widgets['sidebar-1'] );
if( $key ) {
unset( $sidebars_widgets['sidebar-1'][$key] );
}
}
    }
    return $sidebars_widgets;
}

You may also like