Home>Support>Restrict some widgets to certain post type

Restrict some widgets to certain post type

Hello,

I usually make widgets and i’m working a lot with custom post types.
Today, i’m trying to make a widget available to the user according to the type of the current edited post.

Basically, i would like to have widget “A” available when editing a page but not when editing a post. And conversly a Widget “B” available when editing a post but not when editing a page.

I try to load widget conditionnaly in the “siteorigin_widgets_widget_folders” filter.
It works well for the panel “Add new Widget” but i cannot get the widget form.


function cc_sk_widgets_collection( $folders ) {

global $pagenow ;

if( is_admin() ) {

// Work well for the "add new widget" panel
// Not working to get the inner form of the widget
if( 'post.php' === $pagenow && isset($_GET['post']) ) {
if ( 'post-a' === get_post_type( $_GET['post'] ) {
$folders[] = plugin_dir_path(__FILE__).'so-widgets-A/';
}
if ( 'post-b' === get_post_type( $_GET['post'] ) {
$folders[] = plugin_dir_path(__FILE__).'so-widgets-B/';
}
}

} else {
// always register widgets for frontend
$folders[] = plugin_dir_path(__FILE__).'so-widgets-A/';
$folders[] = plugin_dir_path(__FILE__).'so-widgets-B/';
}

// these widgets are shared to all post type
$folders[] = plugin_dir_path(__FILE__).'so-widgets-C/';

return $folders ;
}
add_filter('siteorigin_widgets_widget_folders', 'cc_sk_widgets_collection');

This is our free support forum. Replies can take several days. If you need fast email support, please purchase a SiteOrigin Premium license.

  1. 7 months, 20 days ago Alex S
    Hi, I Work Here

    Hi Corcules,

    Thanks for getting in touch. I recommend using the siteorigin_panels_widgets filter to do this. For example:

    add_filter( 'siteorigin_panels_widgets', function( $widgets ) {
    	global $post;
    	if ( ! empty( $post ) ) {
    		// Filter widgets based on $post->post_type
    	}
    	return $widgets;
    } );
    

    Kind regards,
    Alex

  2. 7 months, 20 days ago corcules

    Hello Alex, yes that’s the way, works perfectly, thank you !

  3. 7 months, 19 days ago Alex S
    Hi, I Work Here

    Hi Corcules,

    It’s great to hear that helped! :)
    Please feel free to open a new thread if anything else comes up.

    Kind regards,
    Alex

Replies on this thread are closed. Please create a new thread if you have a question, or purchase a SiteOrigin Premium license if you need one-on-one email support.

Get The Most Out of SiteOrigin with SiteOrigin Premium

Find Out More