在wordpress中查找并替换html标头标签

时间:2016-09-27 17:12:16

标签: php wordpress function

是否可以使用函数在标题中查找和替换html标记?

以下是我需要做的事情:

我正在使用wpseo plugin,我将默认设置为无索引的档案子页。

但我有一些类别,我希望将子页面编入索引,并且插件会将noindex标记添加到所有类别中。

因此,我需要找到此标记<meta name="robots" content="noindex,follow">并将其替换为<meta name="robots" content="index,follow"> 仅用这些特定类别。

即:

// First I need to get the url
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

// Now I will check if I'm on category and if current url has the word "page"
// This way, I know I'm on the next pages of the category

if (is_category(array(561) &&  strpos($url,'page') !== false)) {
// If I'm on paged content of category 561

    => FIND THIS: <meta name="robots" content="noindex,follow">
    => REPLACE WITH: <meta name="robots" content="index,follow">';

我该怎么做?

1 个答案:

答案 0 :(得分:3)

你可以像这样挂钩WP SEO'wpseo_robots'钩子:

<?php
// add the filter using an anonymous function
add_filter( 'wpseo_robots', function ( $robotsstr ) {

  if ( is_category(array(561) ) &&  ! is_paged() ) {

    $robotsstr = '<meta name="robots" content="index,follow">';

  }

  return $robotsstr;

}, 10, 1 );

...或更多“传统上喜欢这样:

function SO_39730632_amend_robots ( $robotsstr ) {

  if ( is_category(array(561) ) &&  ! is_paged() ) {

    $robotsstr = '<meta name="robots" content="index,follow">';

  }

  return $robotsstr;

}

add_filter( 'wpseo_robots', 'SO_39730632_amend_robots', 10, 1 );

is_paged()功能应该为您处理分页检查。