Jump to content
Sign in to follow this  
Alejandro

How to programatically disable widgetss in specific posts and pages

Recommended Posts

Alejandro

If you are using WordPress and If you need to hide all widgets or specific widget positions in some pages or posts, there are 3rd party plugins that allow you to do this. However, sometimes these plugins hide the output of the widget, but they do it in a way that the theme doesn't know the widget output is hidden and still shows the sidebar. Below you'll find two possible solutions you can use and you can also combine them.

 

You will add this code in your theme's functions.php file.

 

You need to get the page/post ID where you want to hide the widgets. In the examples below it's 500. You can find this ID when you edit a post/page since it appears in the URL with the "post" parameter:

 

/wp-admin/post.php?post=500&action=edit

 

If you want to hide the widgets on more than one page/post you can add more than one value in the $hideInPostIds array. The same goes for hiding more than one widget position in $hidePositions;

 

Hiding all widgets in a specific page:

function disable_all_widgets( $sidebars_widgets ) {

    global $post;

    $hideInPostIds = array(500,501);

    if ( isset($post) && in_array($post->ID,$hideInPostIds ) )
    {
        $sidebars_widgets = array( false );
    }

    return $sidebars_widgets;
}

add_filter( 'sidebars_widgets', 'disable_all_widgets' );

Hiding only certain widget positions in specific pages:

 

To find out the widget position ID you can look in the browser source in the WordPress dasboard Widgets page.

 

post-2-0-34825100-1517492204.jpg

function disable_widget_positions( $sidebars_widgets ) {

    global $post;

    $hideInPostIds = array(500,501);

    $hidePositions = array('position-5','position-6');

    if ( isset($post) && in_array($post->ID,$hideInPostIds ) )
    {
        foreach ($hidePositions AS $position)
        {
            unset($sidebars_widgets[$position]);
        }
    }

    return $sidebars_widgets;
}

add_filter( 'sidebars_widgets', 'disable_widget_positions' );

widget-position-id.jpg

Share this post


Link to post
Raymond Ringston

This section is only visible with a valid subscription. If you have a valid subscription, please login.

Share this post


Link to post
Sign in to follow this  

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. Please refer to our Privacy Policy.