How to Automatically Create Meta Descriptions from the_content in WordPress

Home » Snippets » How to Automatically Create Meta Descriptions from the_content 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

Are you tired of manually writing meta descriptions for your WordPress website? Crafting unique and compelling meta descriptions can be time-consuming and daunting, especially if you have a large amount of content to optimize. But what if there was a way to automatically generate meta descriptions based on the content of your posts? In this article, we will explore how to automatically create meta descriptions from the_content in WordPress, saving you time and effort while still ensuring that your website’s SEO is up to par.

					function wpturbo_auto_generate_meta_description($content) {
    $excerpt = wp_trim_words($content, 20, '');
    return $excerpt;
}
add_filter('the_content', 'wpturbo_auto_generate_meta_description');
				

The code snippet provided above allows you to automatically create a meta description for your WordPress website by extracting a portion of the content of each page or post.

To begin, we define a new function called wpturbo_auto_generate_meta_description(). This function takes the $content parameter, which represents the content of the page or post where it is being called. The purpose of this function is to generate a custom meta description by extracting a specific portion of the content.

Inside the function, we use the wp_trim_words() function to extract a specific number of words from the content. In this case, we are trimming it to 20 words. The wp_trim_words() function is a built-in WordPress function that allows you to extract a specific number of words from a given text.

After extracting the desired portion of the content, we return it using the return statement. This means that the extracted portion will be used as the meta description for the specific page or post.

The next step is to hook the wpturbo_auto_generate_meta_description() function into the the_content filter. The the_content filter is a WordPress filter that allows you to modify the content of a post or page before it is displayed. By hooking our function into this filter, we ensure that the custom meta description is automatically generated and applied to the content of each page or post.

By using this code snippet, you no longer have to manually write custom meta descriptions for each page or post on your WordPress website. Instead, the code will extract a portion of the content and use it as the meta description, making it more efficient and less time-consuming.

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