Disable widgets on specific posts

I run a horror related blog. Google is upset with me for displaying adsense in a sidebar widget for one specific post number (4603) that contains an article about an 18+ topic. How can I disable the widgets for a specific id?

Related posts

Leave a Reply

3 comments

  1. You can filter sidebars_widgets and remove the widget you don’t need.

    Example with a search widget; uncomment the debug code to find the correct identifier.

    if ( ! is_admin() )
        add_filter( 'sidebars_widgets', 'remove_specific_widget' );
    
    function remove_specific_widget( $widgets )
    {
        if ( ! is_single( 402 ) ) // Post ID, title, slug, or array of such
            return $widgets;
    
        if ( ( $key = array_search( 'search-3', $widgets['primary-widget-area'] ) ) !== FALSE ) {
            unset( $widgets['primary-widget-area'][ $key ] );
        }
    
        // use this to inspect the current widget parameters
        //print '<pre>$widgets = ' . htmlspecialchars( var_export( $widgets, TRUE ), ENT_QUOTES, 'utf-8', FALSE ) . '</pre>';
    
        return $widgets;
    }