目次
< 記事一覧

【WP】プラグイン無しで記事ごとにnoindexを設定する

◆functions.phpに記述すること。
「page」「works」「faq」などの部分を任意のタクソノミー名に変更する。

  

//////////////////////////////////
// index操作
//////////////////////////////////
add_action( 'admin_menu', 'st_stmeta_robots_add_metaboxr' );
add_action( 'save_post', 'st_stmeta_robots_save_stmeta_robots' );
function st_stmeta_robots_add_metaboxr() {
//必要なタクソノミーを追加
  add_meta_box( 'stmeta', 'index変更', 'st_stmeta_robots_stmeta_robots_dropdown_box', 'page', 'side', 'low' );
  add_meta_box( 'stmeta', 'index変更', 'st_stmeta_robots_stmeta_robots_dropdown_box', 'works', 'side', 'low' );
  add_meta_box( 'stmeta', 'index変更', 'st_stmeta_robots_stmeta_robots_dropdown_box', 'faq', 'side', 'low' );
}

// 挿入ページ
function st_stmeta_robots_stmeta_robots_dropdown_box() {
  global $post;
  wp_nonce_field( wp_create_nonce( __FILE__ ), 'st_stmeta_robots' );
  $stmeta_robots = $post->stmeta_robots;
?>
<label for="stmeta_robots"></label>
<select name="stmeta_robots" id="stmeta_robots">
  <option <?php if ( $stmeta_robots === "index, follow" ) {
    echo 'selected="selected"';
  } ?>>index, follow
  </option>
  <option <?php if ( $stmeta_robots === "index, nofollow" ) {
    echo 'selected="selected"';
  } ?>>index, nofollow
  </option>
  <option <?php if ( $stmeta_robots === "noindex, follow" ) {
    echo 'selected="selected"';
  } ?>>noindex, follow
  </option>
  <option <?php if ( $stmeta_robots === "noindex, nofollow" ) {
    echo 'selected="selected"';
  } ?>>noindex, nofollow
  </option>
</select>
<?php
}

// データベース登録
function st_stmeta_robots_save_stmeta_robots( $post_id ) {
  $my_nonce = isset( $_POST['st_stmeta_robots'] ) ? $_POST['st_stmeta_robots'] : null;
  if ( !wp_verify_nonce( $my_nonce, wp_create_nonce( __FILE__ ) ) ) {
    return $post_id;
  }
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
    return $post_id;
  }
  if ( !current_user_can( 'edit_post', $post_id ) ) {
    return $post_id;
  }
  $data = $_POST['stmeta_robots'];
  if ( get_post_meta( $post_id, 'stmeta_robots' ) === "" ) {
    add_post_meta( $post_id, 'stmeta_robots', $data, true );
  } elseif ( $data !== get_post_meta( $post_id, 'stmeta_robots', true ) ) {
    update_post_meta( $post_id, 'stmeta_robots', $data );
  } elseif ( $data === "" ) {
    delete_post_meta( $post_id, 'stmeta_robots', get_post_meta( $post_id, 'stmeta_robots', true ) );
  }
}

// 表示
function st_stmeta_robots_add_stmeta_robots_tag() {
  global $post;
  if ( is_single() || is_page() ) {
    if ( ( $GLOBALS["stdata9"] ) !== '' &&  ( $GLOBALS["stdata9"] ) != $post->ID ) {
      $stmeta_robots = ( empty( $post->stmeta_robots ) ) ? 'index, follow' : $post->stmeta_robots;
      echo '<meta name="robots" content="' . $stmeta_robots . '" />' . "\n";
    }
  } elseif ( !is_category() && is_archive() ) {
    echo '<meta name="robots" content="noindex, follow" />' . "\n";
  } else {
  }
}
add_action( 'wp_head', 'st_stmeta_robots_add_stmeta_robots_tag' );

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です