How to remove widgets from specific pages

Sometimes when you install a new widget on your WordPress website, you want that widget only on one page, or maybe you want to hide the widget only from your contact or some other page. That will differ from project to project, and if you work on new WordPress websites often, this little code might save you some trouble.

Without any further ado, here’s a snippet which will help you remove widgets from specific pages.

Add/remove widgets on a specific pages:

  1. Open functions.php file
  2. Copy and paste the following code:
  3. add_filter( 'widget_display_callback', 'hide_widget_pages', 10, 3 );
    function hide_widget_pages( $instance, $widget, $args ) {
    if ( $widget->id_base == 'pages' ) {
    if ( !is_page( 'contact' ) ) {
    return false;
    }
    }
    }
  4. Save changes

To customize the code, you will need to find a widget’s ID name and the name of the page from which you want to exclude the widget.

To find the widget ID, you can go through the HTML code of your website simply by inspecting the elements/viewing the source code. Also, you can install a simple plugin which will insert a widget ID name on the bottom of every widget or you can install the function yourself.

Also, you will need a page name for which you want selected widget to appear. You can simply navigate to Pages->All Pages and find the name of you need.

Don’t forget that is_page accepts arrays of names which mean you can write more than one page name directly into brackets and choose multiple pages on which the chosen widget will appear.

Did you know that you can easily remove any of the default WordPress widgets?

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *