如何使用noindex,nofollow在特定wordpress页面上



我想阻止特定页面在片段中的 wp 中索引。尝试了以下内容,但元没有出现在标题中

add_action( 'wp_head', function() {
if ($post->ID == 7407 || $post->ID == 7640 || $post->ID == 7660) {
echo '<meta name="robots" content="noindex, nofollow">';
}
} );

有什么想法吗?

这里有一个变量范围问题:除非您使用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对象并不总是可用的:它仅在实际查看postpage或自定义帖子类型时设置。如果您尝试按原样使用此代码,它将在未设置$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">';
}
} );

我已经使用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' );

最新更新