Adding Automatic Meta Description in WordPress using PHP

Tiempo de lectura: < 1 minuto

Reading time: < 1 minute

Following up on the previous tutorial on Adding Automatic Meta Keywords in WordPress using PHP, I’m going to show you how to add an automatic meta description in WordPress using PHP.

To add the description automatically, we will use the article’s title and add it to the head section.

The first thing we need to do is go to Appearance > Theme Editor and then edit functions.php.

Inside this PHP class, we are going to add a method called generate_description() within if ( ! function_exists( 'generate_setup' ) ) {:

if ( ! function_exists( 'generate_setup' ) ) {
bash
Copy code
    function generate_description(){


}

Now, let me explain this simple code.

The line $title = get_the_title(); is responsible for retrieving the title of the current post and storing it in the $title variable.

Then, in the line echo '<meta name="description" content="' . $title . '" />'; we use echo to output the meta name=”description” with the added post title. This way, we use that title as the content of the current page.

To use this code in our created posts, we invoke the function by calling it from the header.php file.

<head>
...
</head>

This is a quick way to add and improve the SEO of our WordPress site.

In future tutorials, I will enhance the script to obtain the description using the content of the post itself, not just the title.

Leave a Comment