Add custom meta tags to WordPress posts & pages

Home / Add custom meta tags to WordPress posts & pages

code coder coding

I’m still new to WordPress development put plugging along at a good pace. We recently started developing our business toward online marketing and web development, which has pushed me into this domain. In out custom themes we want the ability to add specific meta tags to the page header for SEO.

There are actually paid plugins that do exactly this. In my case I’m building it into a custom theme, but it could easily be a standalone plugin you could drop into any project.

This is what I’ve got so far…

In my themes functions.php I’ve created a new class to wrap all the functions necessary.

abstract class MyTheme_Meta_Box
{
....
}

I’ve then defined a array of meta tags we want to be available on a per post basis.

....
private static $fields = [
        // Search Engine
        "name=description",
        "name=image",
        // Schema.org for Google
        "itemprop=name",
        "itemprop=description",
        "itemprop=image",
        //  Twitter
        "name=twitter:card",
        "name=twitter:title",
        "name=twitter:description",
        "name=twitter:image:src",
        // Open Graph general (Facebook, Pinterest & Google+)
        "name=og:title",
        "name=og:description",
        "name=og:image",
        "name=og:url",
        "name=og:site_name",
        "name=og:locale",
        "name=og:type",
    ];
....

The next step was to define the function to add the metabox to the page editor and define the html.

    public static function add()
    {
        $pagetypes = ['post', 'page'];
        foreach ($pagetypes as $pagetype) {
            add_meta_box(
                'MyTheme_box_id',        
                'Custom Meta Data',      
                [self::class, 'html'],   
                $pagetype                
            );
        }
    }

    public static function html($post)
    {
        foreach (self::$fields as $field) {
            $value = get_post_meta($post->ID, $field, true);
            ?>
            <label for="<?php echo $field ?>"><?php echo $field ?></label>
            <input name="<?php echo $field ?>" id="<?php echo $field ?>" value="<?php echo $value ?>" style="width: 100%">
            <br>
        <?php
        }
    }

At this point we could register the function, but we’ll save that for the end and add them all at once. We also need to add a function to handle saving the new data to the database.

The official documentation has multiple ways of doing this, but recommends using the update function as such:

    public static function save($post_id)
    {
        foreach (self::$fields as $field) {
            if (array_key_exists($field, $_POST)) {
                update_post_meta(
                    $post_id,
                    $field,
                    $_POST[$field]
                );
            }
        }
    }

With that, all the data is saved. Looking at it now, I should probably put in a step to remove empty tags from the database. Mental note for later.

We now need a function to pull and display that data, which can be hooked into wp_head.

public static function head()
    {
        foreach (self::$fields as $field) {
            // get meta key
            $value = get_post_meta(get_queried_object_id(), $field, true);

            //Output
            if (!empty($value)) {
                printf(
                    '<meta %s content="%s" />',
                    esc_attr((trim($field))),
                    esc_attr((trim($value)))
                );
            }
        }
    }

The only thing left to do is register the functions on the appropriate hooks. This we do outside of the class, if there is any confusion.

add_action('add_meta_boxes', ['MyTheme_Meta_Box', 'add']);
add_action('save_post', ['MyTheme_Meta_Box', 'save']);
add_action('wp_head', ['MyTheme_Meta_Box', 'head']);

That’s it, all the meta fields will now be displayed in the header if they aren’t empty.

,

About Author

about author

Wayne

Jack of all trades. I.T. edition. Programmer, Systems Administrator, DevOps and whatever else comes up.