Search code examples
phphtmlwordpressmeta

Correctly set meta description in header.php


I'm building a website with wordpress and a bought template. I added some functionality to the options/page creation. One can set a general meta description in the options and a meta description for each page while creating it.

Although I'm entirely new to PHP, I managed to add everything necessary to my code. It wasn't all that hard and it works just fine. My questions are: Am I doing it right? How can I optimize my solution? What are the downsides of my approach?

HTML (header.php):

<?php
// Defining a global variable
global $page_meta_description;

// Initializing the variable with the set value from the page
$page_meta_description= get_post_meta($post->ID, MTHEME . '_page_meta_description', true);

// Add meta tag if the variable isn't empty
if ( $page_meta_description != "" ) { ?>
    <meta name="description" content="<?php echo $page_meta_description; ?>" />

<?php }

// Otherwise add globally set meta description
else if ( of_get_option('main_meta_description') ) { ?>
    <meta name="description" content="<?php echo of_get_option('main_meta_description'); ?>" />
<?php }

// Set global meta keywords
if ( of_get_option('main_meta_keywords') ) { ?>
    <meta name="keywords" content="<?php echo of_get_option('main_meta_keywords'); ?>" />
<?php } ?>

Solution

  • You can use the wp_head hook.

    // write this in your plugin
    add_action('wp_head', 'myplugin_get_meta_tags');
    
    function myplugin_get_meta_tags()
    {
        $content = '';
        $content .= '<!-- add meta tags here -->';
        return $content;
    }
    

    I think this is slightly more elegant that doing all the logic in the header.php file.

    If you don't want to create a plugin for this, or it's needed for a single theme, you can add this code in the functions.php file in your theme (check the link for more info).

    Note

    The downside(s) to your solution are:

    • If you ever need to create a new template that uses a different header, you need to copy the meta code to each new file, and when you make changes, make them in all header files
    • The template files should have as little logic in them as possible, and having a bunch of ifs would clutter it unnecessarily.