• On my dev site I have a custom post type with a metadata date field. The date is stored as YYYY-MM-DD. I have a filter which converts this to date format “jS M, Y” for display –


    function s25_filter_event_fields($metadata, $object_id, $meta_key, $single){
    if('event_date' === $meta_key){
    /* $metadata is always null -
    remove filter to prevent infinite loop when retrieving value
    */
    remove_filter( 'get_post_metadata', 's25_filter_event_fields', 10 );
    $current_meta = get_post_meta( $object_id, 'event_date', TRUE );
    /* reinstate the filter now that we have got the value */
    add_filter('get_post_metadata', 's25_filter_event_fields', 10, 4);
    $date = strtotime($current_meta);

    $newdate = date("jS M, Y", $date);

    return $newdate;
    }
    }

    add_filter('get_post_metadata', 's25_filter_event_fields', 10, 4);

    The filter runs on the front end and on the Gutenberg editor correctly but I also have a custom input control in the editor :-

    registerPlugin( 'event-controls', {
    render: () => {
    // Add your custom code here.
    const postType = useSelect(
    ( select ) => select( 'core/editor' ).getCurrentPostType(),
    []
    );

    const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );

    if ( 'event' !== postType ) {
    return null;
    }
    return (
    <PluginDocumentSettingPanel
    title={ 'Event info' }
    >
    <VStack>
    <InputControl
    label={ 'Event Date' }
    value={ meta?.event_date }
    onChange={ ( value ) => setMeta( {
    ...meta,
    event_date: value || null
    } ) }
    />
    </VStack>
    </PluginDocumentSettingPanel>
    );
    }
    } );

    The filter also runs in the input control which breaks the storing of the metadata.

    Is there any way to either :-

    • (the best option) prevent the filter from being applied to the input control? or
    • (second best) prevent the filter from being applied in the Gutenberg editor?
Viewing 1 replies (of 1 total)
  • Thread Starter wwccscorer

    (@wwccscorer)

    After more research, the following added at the beginning of the filter gives me the 2nd option from above (no filtering at all in the editor)

        if(strstr($_SERVER['REQUEST_URI'], 'wp-admin/post-new.php') ||
    strstr($_SERVER['REQUEST_URI'], 'wp-admin/post.php') ||
    strstr($_SERVER['REQUEST_URI'], '/wp-json/wp/v2/')){
    return $metadata;
    }

    but this seems a bit of a hack. If anyone knows a better way to do this, I’d be grateful to hear from you.

Viewing 1 replies (of 1 total)

You must be logged in to reply to this topic.