Home>Support>Hiding/showing fields based on post type

Hiding/showing fields based on post type

By C, 2 months ago. Last reply by C, 2 months ago.

Hi,

I’ve asked a similar question before but I went off on a bit of a tangent!

I’m wondering how to alter the fields shown in a widget based on the context of the post being edited. Using GET[‘post’] doesn’t work, I think due to the use of caching and/or ajax. I’ve tried that both in get_widget_form and using the ‘siteorigin_widgets_form_options_…’ filter.

Is there a best practice approach to achieve this or is it generally recommended not to modify widgets on the fly in this way?

Any other ideas to achieve what I’m after would be appreciated.

Thanks

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

  1. 2 months, 19 hours ago Alex S
    Hi, I Work Here

    Hi C,

    Thanks for getting in touch. This is possible using the `siteorigin_widgets_form_options_WIDGETBASEID` filter. This filter is applied after caching, so you don’t need to worry about the wrong fields being cached.

    As an example of how to use this filter, here’s adding a Color field to the SiteOrigin Editor widget if the current post type is page.

    add_filter( 'siteorigin_widgets_form_options_sow-editor', function( $form_options ) {
    			if ( empty( $_POST['postId'] || ! is_numeric( $_POST['postId'] ) ) ) {
    				return $form_options;
    			}
    
    			$post_type = get_post_type( (int) $_POST['postId'] );
    			if ( $post_type === 'page' ) {
    				$form_options['color'] = array(
    					'type' => 'color',
    					'label' => __( 'Color', 'so-docs' ),
    					'default' => '#000000',
    				);
    			}
    
    			return $form_options;
    		} );
    

    Kind regards,
    Alex

  2. 2 months, 14 minutes ago C

    Hi Alex,

    Well that’s annoying, I could have sworn I’d tried this! I guess I wasn’t using $_POST[‘postId’].

    Anyway, thanks very much, I’ll keep that in mind for the future.

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