如何在特定的 WordPress 页面使用 noindex、nofollow

问题描述 投票:0回答:5

我想阻止特定页面在片段中的 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
5个回答
0
投票

这里存在变量作用域问题:除非使用

$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(7407) || is_page(7640) || is_page(7660)) {
        echo '<meta name="robots" content="noindex, nofollow">';
    }
} );

0
投票

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

0
投票

为了便于理解单个 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' );

重要提示: 在发布帖子时,请确保该帖子是“公开的”。如果帖子是“私人”,则此代码将不起作用。


0
投票
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' );

0
投票

/* Add the code directly to the functions.php file of your active WordPress theme.
 */
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">';
     }
});

© www.soinside.com 2019 - 2024. All rights reserved.