Show Widgets Only on Certain Page Types
Adds a "Show on" setting to every classic widget, so you can limit it to the homepage, single posts, blog and archive pages, or everywhere except those.
Opens WPIDE on
Code
// Choices for the "Show on" setting added to every classic widget.
$wpide_widget_contexts = array(
'' => 'All pages',
'front' => 'Homepage only',
'not_front' => 'Everywhere except the homepage',
'singular' => 'Single posts and pages',
'posts' => 'Single blog posts only',
'lists' => 'Blog, archive and search pages',
'not_lists' => 'Everywhere except blog, archive and search pages',
);
add_action( 'in_widget_form', function ( $widget, $return, $instance ) use ( $wpide_widget_contexts ) {
$value = isset( $instance['wpide_show_on'] ) ? $instance['wpide_show_on'] : '';
$id = $widget->get_field_id( 'wpide_show_on' );
echo '<p><label for="' . esc_attr( $id ) . '">Show on:</label> <select class="widefat" id="' . esc_attr( $id ) . '" name="' . esc_attr( $widget->get_field_name( 'wpide_show_on' ) ) . '">';
foreach ( $wpide_widget_contexts as $key => $label ) {
echo '<option value="' . esc_attr( $key ) . '"' . selected( $value, $key, false ) . '>' . esc_html( $label ) . '</option>';
}
echo '</select></p>';
}, 10, 3 );
add_filter( 'widget_update_callback', function ( $instance, $new_instance ) use ( $wpide_widget_contexts ) {
$value = isset( $new_instance['wpide_show_on'] ) ? sanitize_key( $new_instance['wpide_show_on'] ) : '';
$instance['wpide_show_on'] = isset( $wpide_widget_contexts[ $value ] ) ? $value : '';
return $instance;
}, 10, 2 );
add_filter( 'widget_display_callback', function ( $instance ) {
if ( ! is_array( $instance ) || empty( $instance['wpide_show_on'] ) || is_admin() ) {
return $instance;
}
$is_list = is_home() || is_archive() || is_search();
switch ( $instance['wpide_show_on'] ) {
case 'front':
$show = is_front_page();
break;
case 'not_front':
$show = ! is_front_page();
break;
case 'singular':
$show = is_singular();
break;
case 'posts':
$show = is_singular( 'post' );
break;
case 'lists':
$show = $is_list;
break;
case 'not_lists':
$show = ! $is_list;
break;
default:
$show = true;
}
return $show ? $instance : false;
} );
Notes
Works with classic widgets and the Legacy Widget block; block widgets do not get the setting.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.