WordPress at a glance

get_the_excerpt() WP 0.71

Retrieves the excerpt of current or defined post. By default, should be used in WordPress Loop.

To display post excerpt to the screen, you can use the_excerpt(), it also adds an HTML paragraph (<p></p>) to the post snippet (excerpt).

Notes:

  • Since 4.5.0 Introduced the $post parameter.
Is the basis for: the_excerpt_rss(), the_excerpt()
Hooks from function:
Return

String.

  • If post_excerpt is not specified for the post, then the starting fragment of the current post content will be retrieved. For more information, see wp_trim_excerpt() code. Therefore, to check if the post has an excerpt, use has_excerpt().

  • If "quote" (excerpt) is specified, the value of the "quote" field will be returned.

  • For posts protected by a password, always returns a line with the text: "There is no excerpt because this is a protected post.".

Usage

get_the_excerpt( $post );
$post(int/WP_Post)
Post ID or WP_Post object.
Default: global $post

Examples

#1 Let's check if there is an excerpt.

If the quote is not specified, then display custom text:

$my_excerpt = get_the_excerpt();
if( $my_excerpt ){
	echo wpautop( $my_excerpt );
}
else {
	echo wpautop('Citation not established.');
}

#2 Excerpt output with character limit

Use the get_the_excerpt() function to display a quote with a limited maximum of characters:

function the_excerpt_limited( $charlength ){
	$excerpt = get_the_excerpt();

	$charlength++;

	if ( mb_strlen( $excerpt ) > $charlength ) {
		$subex = mb_substr( $excerpt, 0, $charlength - 5 );
		$exwords = explode( ' ', $subex );
		$excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
		if ( $excut < 0 ) {
			echo mb_substr( $subex, 0, $excut );
		} else {
			echo $subex;
		}
		echo '[...]';
	}
	else {
		echo $excerpt;
	}
}

Usage, somewhere in the loop:

<?php the_excerpt_limited( 140 ); ?>

Code of get_the_excerpt: wp-includes/post-template.php VER 4.9.8

<?php
function get_the_excerpt( $post = null ) {
	if ( is_bool( $post ) ) {
		_deprecated_argument( __FUNCTION__, '2.3.0' );
	}

	$post = get_post( $post );
	if ( empty( $post ) ) {
		return '';
	}

	if ( post_password_required( $post ) ) {
		return __( 'There is no excerpt because this is a protected post.' );
	}

	/**
	 * Filters the retrieved post excerpt.
	 *
	 * @since 1.2.0
	 * @since 4.5.0 Introduced the `$post` parameter.
	 *
	 * @param string $post_excerpt The post excerpt.
	 * @param WP_Post $post Post object.
	 */
	return apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );
}

Related Functions

From tag: excerpt (fragment, snippet)

More from tag: WP Loop

More from category: Posts, pages...

No comments
    Hello, !     Log In . Register