【问题标题】:Correctly set meta description in header.php在 header.php 中正确设置元描述
【发布时间】:2013-06-07 07:01:48
【问题描述】:

我正在使用 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 } ?>

【问题讨论】:

  • 不要使用GLOBALS还有其他的方法来传递变量。
  • 如果变量没有在函数中使用,则不必使用global关键字。

标签: php html wordpress meta


【解决方案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 文件中添加此代码(查看链接了解更多信息)。

注意

您的解决方案的缺点是:

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

【讨论】:

  • 你可以创建一个插件,但如果你不想,在你的主题根文件夹的functions.php文件中添加你的代码(如果它不存在,你可以创建它) .
  • 将文件重命名为functions.php :)
  • 只需将代码添加到已经存在的functions.php文件中即可。或者包含你在functions.php中创建的文件
猜你喜欢
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
相关资源
最近更新 更多