Home / functions.php / Show or Hide widgets on specific pages
  • How to Show or Hide widgets on specific pages

    disable-sidebar-widgets-on-specific-posts

    Want to show or hide widgets on specific pages? This is a great little snippet contributed by Joel Worsham that will do just that. You will first need to get the id name of the widget that you wish to define. You can do this be viewing the page source or using a web inspector tool to view the widget id. The current sample is setup to only display the core ‘pages’ widget on the contact page only. Don’t forget that is_page also accepts an array of page names and id’s.

    ( click code to copy )

    wordpress snippet : PHP

    <>
    add_filter( 'widget_display_callback', 'hide_widget_pages', 10, 3 );
    function hide_widget_pages( $instance, $widget, $args ) {
      if ( $widget->id_base == 'pages' ) { // change 'pages' to widget name
         if ( !is_page( 'contact' ) ) {    // change page name
             return false;
         }
      }
    }
    

    ( WordPress codex functions, hooks, in this snippet. )

    get_pages, get_page, is_page, add_filter,
  • I like it. Thanks for sharing.

    Saves installing another plugin.

  • Very useful code. Thanks for sharing.

    • No problem Sajan, Joel Worsham is going be contributing to wpsnipp.com so I’m sure he will have lots of great snippets to come.

  • Awesome Joel! I’ll be looking forward to seeing more of what you’ve been working on.