How to Display Post Excerpts in WordPress Themes

4 days ago, WordPress Themes, 2 Views
How to display post excerpts in WordPress themes

Understanding Post Excerpts in WordPress

WordPress post excerpts are short summaries or teasers of your blog posts. They offer a glimpse of the content, encouraging readers to click through and read the entire article. Excerpts are crucial for improving user experience, especially on archive pages, category pages, and the homepage. They help users quickly scan and decide which articles are relevant to them.

There are two main ways to create excerpts in WordPress:

  • Automatically Generated Excerpts: WordPress can automatically generate excerpts by truncating the beginning of your post content. The length of this automatically generated excerpt is typically around 55 words, but this can be modified (more on that later).
  • Manually Written Excerpts: You can write custom excerpts for each post. This allows you to craft a more engaging and targeted summary that highlights the most important aspects of the article. Manually written excerpts are generally preferred because they offer greater control over the message.

Why Use Excerpts Instead of Full Content?

Displaying full content on archive pages can have several drawbacks:

  • Page Load Speed: Loading full posts on archive pages can significantly increase page load time, especially with many posts. Excerpts reduce the amount of data that needs to be loaded, improving performance.
  • User Experience: Long pages filled with full posts can be overwhelming for users. Excerpts provide a more digestible overview, making it easier for users to browse and find the content they’re looking for.
  • SEO Considerations: Duplicate content issues can arise if the same content is displayed on multiple pages. Excerpts help avoid this by presenting unique summaries on archive pages.
  • Design and Layout: Full posts on archive pages can disrupt the design and layout of your website. Excerpts allow for a cleaner and more organized presentation.

Methods for Displaying Excerpts in WordPress Themes

There are several ways to display excerpts in your WordPress theme, ranging from simple template tag usage to more advanced customization using filters.

Using the `the_excerpt()` Template Tag

The simplest way to display an excerpt is to use the `the_excerpt()` template tag. This tag automatically outputs the excerpt for the current post. If a manual excerpt is available, it will be displayed. If not, WordPress will generate an automatic excerpt.

Here’s how to use it within your theme’s template files (e.g., `index.php`, `archive.php`, `category.php`):

“`php

“`

This code snippet first displays the post title as a link to the full post. Then, it uses `the_excerpt()` to display the excerpt. Finally, it adds a “Read More” link that directs users to the full post.

Checking for Excerpt Existence

Sometimes, you might want to conditionally display the excerpt only if it exists (either manual or automatically generated). You can use the `has_excerpt()` function to check for this.

“`php

“`

This code checks if the current post has an excerpt. If it does, it displays the excerpt and a “Read More” link. If not, it displays the full content of the post, truncated with a “Read More” link.

Using the `get_the_excerpt()` Function

The `get_the_excerpt()` function is similar to `the_excerpt()`, but instead of directly outputting the excerpt, it returns the excerpt as a string. This allows you to manipulate the excerpt before displaying it.

“`php

“`

This code retrieves the excerpt using `get_the_excerpt()` and stores it in the `$excerpt` variable. It then checks if the excerpt is not empty and displays it within a `

` tag. `wp_kses_post` is used to sanitize the output, ensuring only allowed HTML tags are displayed. A “Read More” link is also added.

Customizing the Excerpt Length

You can customize the length of the automatically generated excerpt by using the `excerpt_length` filter. This filter allows you to modify the number of words in the excerpt.

Add the following code to your theme’s `functions.php` file:

“`php
function custom_excerpt_length( $length ) {
return 30; // Change 30 to your desired excerpt length
}
add_filter( ‘excerpt_length’, ‘custom_excerpt_length’, 999 );
“`

This code defines a function `custom_excerpt_length` that returns the desired excerpt length (in this case, 30 words). The `add_filter()` function then hooks this function into the `excerpt_length` filter. The priority `999` ensures that this filter is applied after any other filters that might be modifying the excerpt length.

Changing the Excerpt More Text

The “more” text is the text that is appended to the automatically generated excerpt. By default, this is `[…]`. You can customize this using the `excerpt_more` filter.

Add the following code to your theme’s `functions.php` file:

“`php
function custom_excerpt_more( $more ) {
return ‘ ‘ . __( ‘Read More »’, ‘your-theme-textdomain’ ) . ‘‘;
}
add_filter( ‘excerpt_more’, ‘custom_excerpt_more’ );
“`

This code defines a function `custom_excerpt_more` that returns the desired “more” text. It constructs a link to the full post with the text “Read More »”. The `add_filter()` function then hooks this function into the `excerpt_more` filter. The `__( ‘Read More »’, ‘your-theme-textdomain’ )` function is used for internationalization (allowing you to translate the “Read More” text). Replace ‘your-theme-textdomain’ with your theme’s text domain.

Removing the Default Excerpt More Text

If you want to remove the default `[…]` from automatically generated excerpts completely, you can modify the `custom_excerpt_more` function to return an empty string:

“`php
function custom_excerpt_more( $more ) {
return ”;
}
add_filter( ‘excerpt_more’, ‘custom_excerpt_more’ );
“`

This will remove the default ellipsis. You would typically combine this with adding your own “Read More” link using a different method.

Using `wp_trim_words()` for More Control

The `wp_trim_words()` function provides even more control over the excerpt generation process. It allows you to specify the number of words and the “more” text. You can use this function in conjunction with `get_the_content()` to create custom excerpts.

“`php

Read More‘ ); // Trim to 40 words
echo ‘

‘ . wp_kses_post( $excerpt ) . ‘

‘;
?>

“`

This code retrieves the full post content using `get_the_content()`. It then uses `wp_trim_words()` to trim the content to 40 words and adds a “Read More” link. The resulting excerpt is then displayed. Again, `wp_kses_post` sanitizes the output.

Displaying Excerpts in Custom Post Types

Displaying excerpts for custom post types is the same as displaying them for regular posts. The `the_excerpt()`, `get_the_excerpt()`, `has_excerpt()` functions, and the filters `excerpt_length` and `excerpt_more` all work with custom post types. The key is to ensure that your custom post type supports excerpts.

When registering your custom post type, make sure to include `excerpt` in the `supports` array:

“`php
function register_custom_post_type() {
$args = array(
‘labels’ => array(
‘name’ => ‘My Custom Post Type’,
‘singular_name’ => ‘Custom Post’,
),
‘public’ => true,
‘supports’ => array( ‘title’, ‘editor’, ‘excerpt’, ‘thumbnail’ ), // Include ‘excerpt’
);
register_post_type( ‘custom_post_type’, $args );
}
add_action( ‘init’, ‘register_custom_post_type’ );
“`

By including `excerpt` in the `supports` array, you enable the excerpt meta box in the post editor for your custom post type.

Using Conditional Tags for Different Excerpt Displays

You can use conditional tags to display different excerpts on different pages. For example, you might want to display shorter excerpts on the homepage and longer excerpts on archive pages.

“`php

Read More‘ );
echo ‘

‘ . wp_kses_post( $excerpt ) . ‘

‘;
?>

“`

This code checks if the current page is the homepage or the front page. If it is, it sets the `$excerpt_length` to 20. Otherwise, it sets it to 40. Then, it uses `wp_trim_words()` to generate the excerpt with the appropriate length.

Styling Excerpts with CSS

Excerpts are usually displayed within `

` tags or other HTML elements. You can style these elements using CSS to customize the appearance of your excerpts.

For example, you can add the following CSS to your theme’s stylesheet to style the excerpt text:

“`css
.entry-content p {
font-size: 16px;
line-height: 1.5;
color: #333;
}

.read-more {
color: #007bff;
text-decoration: none;
}

.read-more:hover {
text-decoration: underline;
}
“`

This CSS styles the `

` tags within the `.entry-content` class (which is a common class used to wrap the post content) to have a font size of 16px, a line height of 1.5, and a color of #333. It also styles the “Read More” link to have a blue color and no underline by default, and an underline on hover. Adapt these styles to fit your theme’s design.

Best Practices for Using Excerpts

  • Write compelling manual excerpts: Whenever possible, write custom excerpts that are engaging and accurately reflect the content of the post.
  • Keep excerpts concise: Aim for a length that is appropriate for your website’s design and layout. Generally, 20-50 words is a good range.
  • Include a clear call to action: Always include a “Read More” link or button that encourages users to click through to the full post.
  • Use proper HTML structure: Wrap your excerpts in appropriate HTML elements, such as `

    ` tags, for semantic correctness and styling purposes.

  • Consider mobile responsiveness: Ensure that your excerpts are displayed correctly on different screen sizes.
  • Test and optimize: Experiment with different excerpt lengths and styles to see what works best for your audience.