Register widget only page is a singular of custom post type

I’ve made a custom post type, with a few accompanying widgets, and I was wondering if it is possible to show (some of) these widgets only if you’re on a specific page.

Currently I’ve got

Read More
function widget($args, $instance)
{
    global $post;
    $links = unserialize(get_post_meta( $post->ID, 'links', true ));

    if(!is_singular( 'press_articles' ) || $links == false) {
        unregister_widget( 'Point72_Press_Article_Links_Widget' );
        return false;
    }

    // widget stuff
}

But, that doesn’t seem to completely remove it, and with that I mean, it removes the widget in the right places, but the positions for the widgets stay even if it’s not empty.

So, is there anyway to either remove the empty positions, or not show it at all outside a custom post type?

Related posts

Leave a Reply

2 comments

  1. Instead of nuking the entire widget, you should put your conditional statements within the widget itself:

    public function widget( $args, $instance ) {
         if ( is_singular( array( 'post_type_a', 'post_type_b' ) ) ) {
              // display your widget here
         }
    }
    

    Since you’re not printing $before_widget and $after_widget, there won’t be any output for this widget unless the conditions are met.

  2. Okay, I got it finally! Wouldn’t have been able to without looking at the source of Widget Logic

    This is how it is:
    First register a function to filter on sidebar_widgets:

    add_filter( 'sidebars_widgets', 'my_filter_widgets', 10);
    

    Then loop through all the widgets, skip over the widgets you don’t care about, and if your condition is not met for the widgets you do care about, remove them, like so:

    function my_filter_widgets($sidebars_widgets)
    {
        foreach($sidebars_widgets as $widget_area => $widget_list)
        {
            foreach($widget_list as $pos => $widget_id)
            {
                // We're only after widgets named my_custom_widget, this can vary and you will need to find out, try doing a var_dump() on  $sidebars_widgets
                if(substr($widget_id, 0, 17) != 'my_custom_widget') {
                    continue;
                }
    
                // Those that have not been skipped over, check your condition, and if it doesn't meet the condition, remove it from the $sidebars_widgets array
                if ('press_articles' != get_post_type() || !is_single()) {
                    unset($sidebars_widgets[$widget_area][$pos]);
                }
            }
        }
        return $sidebars_widgets;
    }