【问题标题】:How do I use noindex, nofollow at specific wordpress pages如何在特定的 wordpress 页面上使用 noindex、nofollow
【发布时间】:2020-01-16 03:18:55
【问题描述】:
我想阻止特定页面在 sn-p 中被 wp 索引。尝试了以下,但元数据并没有出现在标题中
add_action( 'wp_head', function() {
if ($post->ID == 7407 || $post->ID == 7640 || $post->ID == 7660) {
echo '<meta name="robots" content="noindex, nofollow">';
}
} );
有什么想法吗?
【问题讨论】:
标签:
wordpress
code-snippets
【解决方案1】:
这里有一个变量范围问题:除非您使用 global 关键字,否则 $post 对象在您的函数中将不可用。
add_action( 'wp_head', function() {
global $post;
if ($post->ID == 7407 || $post->ID == 7640 || $post->ID == 7660) {
echo '<meta name="robots" content="noindex, nofollow">';
}
} );
但是,$post 对象并非始终可用:它仅在实际查看 post、page 或自定义帖子类型时才会设置。如果您尝试按原样使用此代码,它会在未设置 $post 时引发一些 PHP 警告,因此使用 is_page() 函数可能是一个更好的主意,因为该函数会自动为您检查:
add_action( 'wp_head', function() {
if (is_page(7407) || is_page(7640) || is_page(7660)) {
echo '<meta name="robots" content="noindex, nofollow">';
}
} );
【解决方案2】:
我已经使用 wp_robots 过滤器解决了这个问题:
add_filter( 'wp_robots', 'do_nbp_noindex' );
function do_nbp_noindex($robots){
global $post;
if(check some stuff based on the $post){
$robots['noindex'] = true;
$robots['nofollow'] = true;
}
return $robots;
}
【解决方案3】:
为了便于理解单个 WordPress 帖子的 noindex nofollow 函数的确切代码:
function do_the_noindex($robots){
global $post;
if( $post->ID == 26 ) {
$robots['noindex'] = true;
$robots['nofollow'] = true;
}
return $robots;
}
add_filter( 'wp_robots', 'do_the_noindex' );
重要提示:在发布时确保帖子是“公开的”。如果帖子是“私人”,则此代码将不起作用。