Gutenberg select excerpt, use generated excerpt or use more block excerpt

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 );
            },
        });
        }
    );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x