How to Automatically Add Text to the Post Excerpt in WordPress

Home » Snippets » How to Automatically Add Text to the Post Excerpt in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Do you find yourself constantly rewriting the same text for your post excerpts on your WordPress site? Maybe you want to add a disclaimer or call-to-action to every excerpt but don’t want to manually input it every time. Fortunately, there’s a way to automatically add text to your post excerpts without having to do it yourself. In this article, we’ll go over how to set up automatic excerpt text on your WordPress site.

					function WPTurbo_add_text_to_excerpt( $excerpt ) {
    global $post;
    $excerpt_length = strlen( $excerpt );
    $text_to_add = 'Your custom text';
    $text_length = strlen( $text_to_add );
    $new_excerpt_length = $excerpt_length + $text_length;

    // only add text to excerpt if it's short enough
    if ( $new_excerpt_length < 200 ) {
        $excerpt .= $text_to_add;
    }
    return $excerpt;
}
add_filter( 'get_the_excerpt', 'WPTurbo_add_text_to_excerpt' );
				

In this tutorial, I will guide you on how to add text to a post excerpt automatically using the get_the_excerpt filter in WordPress.

This code snippet defines a function called WPTurbo_add_text_to_excerpt that takes the current post's excerpt as a parameter. The global $post object is used to get the excerpt text of the current post.

Next, the strlen() function is used to get the length of the current excerpt. We also define a variable $text_to_add, which contains the custom text that we want to add to the excerpt, and get its length using the same function.

We calculate the new length of the excerpt after adding the custom text by adding the length of the original excerpt and the custom text.

Then, we add a condition that checks if the new excerpt length is less than 200 (you can adjust this number as per your requirements). This ensures that the custom text is only added if the excerpt is short enough to avoid a large amount of content on the archive pages or on the homepage.

Finally, if the condition is met, we concatenate the original excerpt with the custom text using the .= operator and return the new excerpt.

To make the function work, we need to hook it to the get_the_excerpt filter using the add_filter() function, which accepts two parameters: the filter hook we're targeting (get_the_excerpt), and the name of the function that we want to run when the filter is applied (WPTurbo_add_text_to_excerpt).

Once this is done, the custom text will be automatically added to the post excerpt whenever it's generated.

Register an account to save your snippets or go Pro to get more features.