我想阻止特定页面被索引。
尝试了下面的代码,但
robots
元标记没有显示在页面的<header>
部分:
add_action( 'wp_head', function() {
if ($post->ID == 7407 || $post->ID == 7640 || $post->ID == 7660) {
echo '<meta name="robots" content="noindex, nofollow">';
}
} );
有什么想法吗?
这里存在变量作用域问题:除非使用
$post
关键字,否则 global
对象在函数中不可用。
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( array(7407, 7640, 7660) ) ) {
echo '<meta name="robots" content="noindex, nofollow" />';
}
} );
我已经使用 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;
}
为了便于理解单个 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' );
重要提示: 在发布帖子时,请确保该帖子是“公开的”。如果帖子是“私人”,则此代码将不起作用。
function set_noidex_when_sticky($post_id){
if ( wp_is_post_revision( $post_id ) ){
return;
} else{
if( get_post_meta($post_id, '_property_categories', true ) ){
//perform other checks
$status = get_post_meta($post_id, '_property_categories', true );
// var_dump($status);
// die;
//if(is_sticky($post_id)){ -----> this may work only AFTER the post is set to sticky
if ( $status == 'sell') { //this will work if the post IS BEING SET ticky
add_action( 'wpseo_saved_postdata', function() use ( $post_id ) {
// die('test');
update_post_meta( $post_id, '_yoast_wpseo_meta-robots-noindex', '1' );
update_post_meta( $post_id, '_yoast_wpseo_meta-robots-nofollow', '1' );
}, 999 );
}
}
}
}
add_action( 'save_post', 'set_noidex_when_sticky' );
如果不直接在循环外使用全局$post声明,则不能直接使用$post->ID。
<! -- try code it is working fine -->
add_action( 'wp_head', function() {
if(is_page('7407') && get_the_id() == 7407 || is_page('7640') && get_the_id() == 7640 || is_page('7660') && get_the_id() == 7660) {
// Support Parameters Page ID, title, slug, or array of such to check against.
echo '<meta name="robots" content="noindex, nofollow">';
}
});