Using WordPress ‘has_excerpt()’ PHP function

The has_excerpt() WordPress PHP function determines whether a post has a custom excerpt.

Usage

has_excerpt( $post );

Example:

Input:

has_excerpt( 42 );

Output:

true or false

Parameters

  • $post (int|WP_Post) (optional): Post ID or WP_Post object. Default is global $post.

More information

See WordPress Developer Resources: has_excerpt()

Examples

Hiding the auto-generated excerpt

This code will hide the auto-generated excerpt and only display the custom post excerpts.

if ( ! has_excerpt() ) {
  echo '';
} else {
  the_excerpt();
}

Testing for the presence of an excerpt in a post

This code checks whether a post has an excerpt.

// Get $post if you're inside a function.
global $post;
if ( has_excerpt( $post->ID ) ) {
  // This post has an excerpt.
} else {
  // This post has no excerpt.
}

Replacing the auto-generated excerpt with custom text or code

This code replaces the auto-generated excerpt with your custom text or code.

if ( ! has_excerpt() ) :
  // Your text or code.
endif;

Tagged in

Leave a Comment

Your email address will not be published. Required fields are marked *