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 } ?>
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
s would clutter it unnecessarily.