Skip to content

How to Add SEO-Friendly Meta Tags Dynamically in WordPress Using PHP

By ali 13 min read

Adding SEO-friendly meta tags dynamically in WordPress using PHP code

When you manage a WordPress website, you may notice that several pages display the same meta title or meta description in search results. This can happen when your website does not have properly configured SEO metadata.

Every important page should have a title and description that accurately explain its content. Writing these details manually for every post can take time, especially when your website contains hundreds of articles or product pages.

A practical solution is to generate meta descriptions dynamically using PHP. WordPress provides functions and hooks that allow you to retrieve post titles, excerpts, and content and use them to create page-specific metadata.

In this tutorial, you will learn how to:

  • Add dynamic meta descriptions using the wp_head action.
  • Generate descriptions from post excerpts or content.
  • Customize document titles using WordPress filters.
  • Add the functionality through functions.php or a custom plugin.
  • Avoid duplicate metadata when using SEO plugins.
  • Follow basic security and SEO practices when generating metadata.

Why Are Dynamic Meta Tags Important?

Meta tags provide information about a webpage. Search engines can use this information to understand the page, while the title and description may also appear in search results.

For example, imagine your website contains these three articles:

  • How to Create a Custom Plugin in WordPress
  • How to Fix Common WordPress Errors
  • How to Customize WooCommerce Checkout

Each article covers a different topic. If all three pages use the same meta description, visitors may not understand what makes each page different.

Dynamic metadata helps generate page-specific information using existing WordPress content.

You can use:

  • Post title: To create a relevant document title.
  • Post excerpt: To generate a short description.
  • Post content: To create a fallback description when an excerpt is unavailable.
  • Custom fields: To use manually defined SEO descriptions when your project requires them.

Keep in mind that adding meta tags does not guarantee higher rankings. A useful title and description can improve how your pages are presented, but search engines may generate their own snippets depending on the search query.

Where Should You Add Dynamic Meta Tag Code?

There are two common ways to add custom PHP functionality to WordPress.

Option 1: Add Code to functions.php

You can add the code to your active theme’s functions.php file.

This option is suitable when:

  • You are testing a small customization.
  • The functionality is specific to your active theme.
  • You are working on a small website.

However, theme-specific code can stop working when you change themes. Directly editing theme files can also make updates harder to manage.

Option 2: Create a Custom Plugin

A custom plugin is a better option when you want to keep the functionality separate from your theme.

It is useful when:

  • You want the functionality to remain active after changing themes.
  • You plan to reuse the code on multiple websites.
  • You are developing a long-term WordPress project.
  • You want to manage custom functionality independently.

For production websites, I recommend using a custom plugin for reusable functionality.

If you want to learn how to organize your own WordPress functionality, read our guide on creating a custom plugin in WordPress.

Step 1: Understand the wp_head Hook

WordPress provides an action hook called wp_head. It runs inside the HTML document’s <head> section when a properly configured theme calls wp_head().

You can use this hook to output custom meta tags.

Here is a basic example:

add_action( 'wp_head', 'gh_add_dynamic_meta_tags' );

function gh_add_dynamic_meta_tags() {
    // Add custom meta tags here.
}

The callback function runs when WordPress reaches the wp_head hook. You can then check the current page and generate metadata based on its content.

Step 2: Generate a Dynamic Meta Description

Let’s create a function that generates a meta description for individual posts, pages, and other supported singular post types.

The function will:

  • Check whether the current page is a singular post or page.
  • Retrieve the current post.
  • Use the post excerpt when one is available.
  • Use trimmed post content as a fallback.
  • Remove HTML tags and unnecessary spaces.
  • Escape the description before printing it.

Use this PHP code:

function gh_add_dynamic_meta_description() {

    if ( ! is_singular() ) {
        return;
    }

    $post_id = get_queried_object_id();

    if ( ! $post_id ) {
        return;
    }

    $post = get_post( $post_id );

    if ( ! $post ) {
        return;
    }

    // Use the manual excerpt when available.
    $description = get_the_excerpt( $post );

    // Use post content if no excerpt is available.
    if ( empty( trim( $description ) ) ) {
        $description = wp_trim_words(
            $post->post_content,
            25,
            ''
        );
    }

    // Remove HTML tags and normalize whitespace.
    $description = wp_strip_all_tags( $description );
    $description = trim(
        preg_replace( '/\s+/', ' ', $description )
    );

    // Output the meta description.
    if ( ! empty( $description ) ) {
        echo '<meta name="description" content="' .
            esc_attr( $description ) .
            '" />' . "\n";
    }
}

add_action( 'wp_head', 'gh_add_dynamic_meta_description', 1 );

How Does This Code Work?

1. Check the current page:

if ( ! is_singular() ) {
    return;
}

The is_singular() conditional checks whether the current page displays an individual post, page, or supported custom post type. It prevents this function from generating descriptions on archive pages and other non-singular views.

2. Retrieve the current post:

$post_id= get_queried_object_id();
$post= get_post($post_id);

This retrieves the ID and post object for the current queried page. It is a reliable way to get the content used by the current WordPress request.

3. Get the post excerpt:

$description= get_the_excerpt($post);

The function first uses the post excerpt. This gives you control over the description when you have written a manual excerpt for the article.

4. Use content as a fallback:

$description = wp_trim_words(
    $post->post_content,
    25,
    ''
);

If no excerpt is available, the function generates a short description from the post content.

5. Clean and escape the output:

$description= wp_strip_all_tags($description);
echo esc_attr($description);

wp_strip_all_tags() removes HTML tags, while esc_attr() safely escapes the value for use inside an HTML attribute.

The result is a dynamic meta description generated from the current post.

Step 3: Customize the Meta Title Properly

WordPress already has a document title system. You should not manually print another <title> tag through wp_head, because this can create duplicate or conflicting title elements.

WordPress provides the pre_get_document_title filter, which can be used to customize the document title.

Here is an example for singular pages:

function gh_custom_document_title( $title ) {

    if ( is_singular() ) {

        $post_title = get_the_title();

        $site_name = get_bloginfo( 'name' );

        return $post_title . ' | ' . $site_name;
    }

    return $title;
}

add_filter(
    'pre_get_document_title',
    'gh_custom_document_title'
);

For example, if your post title is How to Create a Custom Plugin in WordPress and your website name is GeekerHub, the generated document title will be:

How to Create a Custom Plugin in WordPress| GeekerHub

Important: Use this title filter only when you manage document titles yourself. If you already use Yoast SEO, Rank Math, or another SEO plugin, let that plugin manage your SEO title unless you have a specific integration requirement. Adding another title filter can override or conflict with the SEO plugin’s output.

Step 4: Should You Add the Meta Keywords Tag?

You may have seen websites using a meta keywords tag like this:

<meta name="keywords" content="WordPress, PHP, SEO, meta tags">

For modern Google Search optimization, you do not need to add this tag. Google does not use the keywords meta tag as a ranking signal.

Instead, focus on:

  • Writing descriptive page titles.
  • Creating useful meta descriptions.
  • Publishing relevant and helpful content.
  • Using clear heading structures.
  • Making pages accessible and easy to navigate.

Step 5: Follow These Meta Tag Best Practices

1. Keep Meta Descriptions Useful and Relevant

A meta description should briefly explain what visitors can expect from a page.

There is no fixed character limit that guarantees a complete description in Google search results. Google may truncate or rewrite snippets depending on the device and search query.

As a practical starting point, write concise descriptions that communicate the page topic without unnecessary words. Always review the final text for clarity and accuracy.

2. Always Escape Dynamic Output

Never print content from a post or custom field directly into an HTML attribute without escaping it.

For a meta description, use:

esc_attr($description);

This helps prevent malformed HTML and reduces the risk of unsafe attribute output.

3. Prefer a Manual Excerpt

A manual excerpt gives you more control over the description than automatically extracting text from the article.

Use this order:

  1. Use a custom SEO description if your project provides one.
  2. Otherwise, use the post excerpt.
  3. If neither is available, generate a fallback from the post content.

This approach helps keep descriptions relevant to the actual page.

4. Avoid Duplicate Meta Tags

If your website already uses an SEO plugin such as:

  • Yoast SEO
  • Rank Math
  • All in One SEO

Check the page source before adding another meta description function. These plugins already generate SEO titles and descriptions.

If you add your own code without checking the existing output, your page may contain multiple description tags or conflicting title values.

Choose one system to manage SEO metadata unless you are deliberately building an integration with the existing plugin.

5. Generate Metadata Only on Relevant Pages

Use conditional checks such as:

is_singular()

This helps limit the function to individual posts, pages, and supported custom post types. If you also want descriptions for category archives, search pages, or the homepage, create separate logic for those page types.

functions.php vs Custom Plugin: Which Is Better?

Both methods can work, but the right choice depends on how you plan to maintain the functionality.

  • functions.php: Suitable for theme-specific customizations and quick testing.
  • Custom plugin: Better for reusable functionality that should remain active when the theme changes.

For a production website, I recommend a custom plugin when the metadata functionality is part of your site’s core behavior rather than its design.

Bonus: Create a Simple Dynamic Meta Tags Plugin

Instead of adding the code to your theme, you can create a small plugin that generates meta descriptions for singular pages.

Step 1: Create a plugin folder.

Inside wp-content/plugins/, create a folder named:

geekerhub- dynamic- meta

Step 2: Create the plugin file.

Inside that folder, create a PHP file named:

geekerhub- dynamic- meta. php

Step 3: Add the complete plugin code.

<?php
/**
 * Plugin Name: GeekerHub Dynamic Meta Description
 * Description: Generates dynamic meta descriptions for singular WordPress pages.
 * Version: 1.0.0
 * Author: GeekerHub
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Generate a dynamic meta description.
 */
function gh_add_dynamic_meta_description() {

    if ( ! is_singular() ) {
        return;
    }

    $post_id = get_queried_object_id();

    if ( ! $post_id ) {
        return;
    }

    $post = get_post( $post_id );

    if ( ! $post ) {
        return;
    }

    // Get the post excerpt.
    $description = get_the_excerpt( $post );

    // Use post content if the excerpt is empty.
    if ( empty( trim( $description ) ) ) {
        $description = wp_trim_words(
            $post->post_content,
            25,
            ''
        );
    }

    // Clean the description.
    $description = wp_strip_all_tags( $description );
    $description = trim(
        preg_replace( '/\s+/', ' ', $description )
    );

    // Print the meta description.
    if ( ! empty( $description ) ) {
        echo '<meta name="description" content="' .
            esc_attr( $description ) .
            '" />' . "\n";
    }
}

add_action(
    'wp_head',
    'gh_add_dynamic_meta_description',
    1
);

Step 4: Activate the plugin.

Open your WordPress dashboard and go to Plugins → Installed Plugins. Find GeekerHub Dynamic Meta Description and click Activate.

The plugin will now generate a meta description for individual posts and pages, using the excerpt first and post content as a fallback.

This example handles meta descriptions only. It does not generate SEO titles, and it should not be activated alongside another system that already outputs the same meta description.

Common Mistakes Developers Should Avoid

  • Printing a title tag manually: Use WordPress’s document title system instead of adding another title element.
  • Ignoring existing SEO plugins: Check the page source to avoid duplicate metadata.
  • Skipping output escaping: Always escape dynamic values before printing them into HTML attributes.
  • Using the entire post content: Generate a short, relevant description instead of printing a long article.
  • Adding unnecessary keywords metadata: Focus on useful titles and descriptions rather than the keywords meta tag.
  • Ignoring custom post types: Check whether the post types you want to support are included in your conditional logic.
  • Testing only the dashboard: Inspect the public page source to confirm that the metadata is actually present.

How to Check Whether Dynamic Meta Tags Are Working

After adding the code or activating the plugin, open an individual post on your website.

Then follow these steps:

  1. Open the page in your browser.
  2. Right-click and select View Page Source.
  3. Search for name="description".
  4. Check whether the description matches the current post.
  5. Confirm that only one meta description tag is being generated.
  6. Check the document title and make sure it is correct.

If you use an SEO plugin, check its output as well. The final HTML source is the best place to verify which metadata is actually being sent to the browser.

You can also use Google’s Rich Results Test for supported structured data checks. It is not a general meta description validator, so use your browser’s page source when checking description output.

Final Thoughts

Generating SEO-friendly meta descriptions dynamically can save time when managing a WordPress website with many posts and pages. By using WordPress functions such as get_the_excerpt(), wp_trim_words(), and the wp_head action, you can create page-specific descriptions without editing every post manually.

For reusable functionality, a custom plugin is usually easier to maintain than adding the code directly to your theme. Remember to escape dynamic output, check for existing SEO plugins, and test the generated metadata on the front end.

With a little custom PHP, you can make your WordPress metadata workflow more consistent and easier to manage.