0

I am trying to add the excerpt as a placeholder to a description field in the Gutenberg sidebar. The problem is that when there is no manual added excerpt the placeholder will be empty.

Is there a way to:

  1. get the automatically generated excerpt?
  2. get the paragraph before the "more block" (when it is used)?
  3. if none of the above, how do I select the first block/paragraph without retrieving the complete content?

here is my withSelect code:

    withSelect( function( select, props ) {
        return {
            metaValue: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ props.metaKey ],
            metaExcerpt : select( 'core/editor' ).getEditedPostAttribute( 'excerpt' ),  
            metaContent : select( 'core/editor' ).getEditedPostAttribute( 'content' ),
        }
    } ) )( function( props ) {
        return el( TextareaControl, {
            label: props.title,
            value: props.metaValue,
            placeholder: props.metaExcerpt ? (props.metaExcerpt) : (props.metaContent), 
            help: props.metaExcerpt ? ('') : ('There was no excerpt found'),
            onChange: function( content ) { 
                props.setMetaValue ( content );
            },
        });
        }
    );   
1

get the automatically generated excerpt

The REST API always includes the auto-generated excerpt by default, so try with getEntityRecord() like so:

Note though, if the user edited the actual excerpt (i.e. the "Excerpt" panel in the Settings sidebar and not your metaExcerpt value), then the currentExcerpt would also use the excerpt the user has just edited.

withSelect( function( select, props ) {
    const _post = select( 'core/editor' ).getCurrentPost();
    const post = select( 'core' ).getEntityRecord( 'postType', _post.type, _post.id );

    return {
        metaValue: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ props.metaKey ],
        metaExcerpt : select( 'core/editor' ).getEditedPostAttribute( 'excerpt' ),
        metaContent : select( 'core/editor' ).getEditedPostAttribute( 'content' ),
        currentExcerpt : post ? post.excerpt.rendered : '',
    };
} ... your code.

Then with the TextareaControl, use placeholder: props.metaExcerpt || props.currentExcerpt.

2
  • 1
    well thank you very much! I have learned more from your answers here than from the developer handbook.
    – Leadhood
    Feb 24 at 12:32
  • 1
    I would like to add that I have removed the HTML from the currentExcerpt with .replace(/<[^>]+>/g, '') and removed the [read more] with .replace('[read more]', '')
    – Leadhood
    Feb 24 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.