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

时间:2013-06-07 07:01:48

标签: php html wordpress meta

我正在建立一个带有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 } ?>

1 个答案:

答案 0 :(得分:1)

您可以使用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文件中添加此代码(查看链接以获取更多信息)。 / p>

注意

您的解决方案的缺点是:

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