正确设置header.php中的元描述


Correctly set meta description in header.php

我正在用wordpress和购买的模板建立一个网站。我在选项/页面创建中添加了一些功能。您可以在选项中设置通用元描述,并在创建页面时为每个页面设置元描述。

虽然我对PHP完全陌生,但我设法将所有必要的东西添加到我的代码中。这并没有那么难,而且效果很好。我的问题是:我做得对吗?我如何优化我的解决方案?我的方法有什么缺点?

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 } ?>

可以使用wp_head钩子。

// 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;
}

我认为这比在header.php文件中做所有的逻辑要优雅一些。

如果你不想为此创建一个插件,或者它需要一个单一的主题,你可以在你的主题的functions.php文件中添加这段代码(查看链接以获取更多信息)。

注意

你的解决方案的缺点是:

  • 如果你需要创建一个使用不同头文件的新模板,你需要将元代码复制到每个新文件中,当你进行更改时,在所有头文件中进行更改
  • 模板文件应该有尽可能少的逻辑在他们,并有一堆if将不必要的混乱。