This thread is over two years old and may be outdated. Please create a new thread if you need help, or email us if you have an active Premium license.

Restrict some widgets to certain post type

2 years ago · Last reply by Alex S 2 years ago

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.

Need fast email support? Get SiteOrigin Premium

Replies

3
  1. Alex S Staff 2 years, 3 months ago

    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. corcules 2 years, 3 months ago

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

  3. Alex S Staff 2 years, 3 months ago

    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.

Have a different question or issue?

Start New Thread