Home/ Documentation/ WordPress/ Actions/ Post Excerpt

Post Excerpt

Post Excerpt action displays the excerpt of the current post. If excerpt is not set, WordPress generates a snippet from the post content.

This action can only be used together with Show Posts action.

Post Excerpt action adjusts to the element on which it is placed.

On <p> paragraphs without attributes

When added on a <p> paragraph that has no classes and other attributes, it replaces the whole element with the excerpt formatted in one or more <p> elements.

Why? Because <p> has no attributes we can safely replace it with one or more <p> elements with the excerpt that are generated by WordPress.

For example, adding Post Excerpt on a simple <p> element:

<p>Short description.</p>    <— Post Excerpt

And let’s assume that our excerpt in WordPress is broken in two lines that will be formatted by WordPress into two paragraphs:

This will replace the <p> element with the two paragraphs of the formatted excerpt:

By using the PHP code:

<?php the_excerpt(); ?>

On elements that contain <p> paragraphs

When added on an element that contains <p> paragraph(s) it replaces the content of the element with the excerpt formatted with <p> elements.

Why? Post Excerpt is placed on a container. Any styling is probably also done on the container itself, not on individual <p> excerpt paragraphs. So we can safely fill the content of the container with the formatted excerpt.

Adding the Post Excerpt action on a <div> that contains paragraphs:

<div class="lead">     <— Post Excerpt
    <p>Short description.</p>
</div>

Will output the formatted excerpt inside the <div>:

With the PHP code:

<div class="lead">
    <?php the_excerpt(); ?>
</div>

On all other elements

In all other cases it replaces the content of the element with the text of the excerpt, without formatting it with <p> elements.

Why? Replacing the element with formatted excerpt (one or more <p> paragraphs) would change the tag name of the element at this position, and override any classes or ids that might be used for CSS styling. So, instead, we just output the excerpt as unformatted text in the content of the element.

For example, when used on <p> with class “lead”:

<p class="lead">Short description.</p>    <— Post Excerpt

The action will replace the content of the paragraph with unformatted excerpt, so that the class “lead” remains on the paragraph:

The PHP code:

<p class="lead"><?php echo get_the_excerpt() ?></p>

Only showing the excerpt if it is set

In addition we can check the “Only display if excerpt is set” in order to show the element only when the post has the excerpt. With this we can avoid showing WordPress generated excerpt snippet in cases when the excerpt is not set.

To customize how this action works, click on the icon next to the action name to change it into regular WordPress actions.



Last updated on June 4, 2019 at 6:15 pm


Print this article