function add_post_custombox()
{
$custom_key = "mykey" ;
$noncename = $custom_key . "noncename" ;
global $post;
echo '<input type="hidden" name="' . $noncename . '" id="' . $noncename . '" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />' ;
echo '<label class="screen-reader-text" for="' . $custom_key . '">' . $custom_key . '</label> ' ;
echo '<input type="text" name="' . $custom_key . '" value="' . esc_attr( get_post_meta( $post->ID, $custom_key, true )) . '" size="15" />' ;
}
function save_post_custombox( $post_id )
{
$custom_key = "mykey" ;
$noncename = $custom_key . "noncename" ;
if ( !wp_verify_nonce( $_POST[$noncename], plugin_basename(__FILE__) )) {
return $post_id;
}
if ( !current_user_can( 'edit_post', $post_id )) {
return $post_id;
}
$keywords = esc_attr( $_POST[$custom_key] ) ;
if ( "" == get_post_meta( $post_id, $custom_key )) {
add_post_meta( $post_id, $custom_key, $keywords, true ) ;
} else if ( $keywords != get_post_meta( $post_id, $custom_key )) {
update_post_meta( $post_id, $custom_key, $keywords ) ;
} else if ( "" == $keywords ) {
delete_post_meta( $post_id, $custom_key ) ;
}
}
function admin_menu_custombox()
{
add_meta_box( 'mykeybox', 'mybox', 'add_post_custombox', 'post', 'normal', 'low' ) ;
}
add_action( 'admin_menu', 'admin_menu_custombox' ) ;
add_action( 'save_post', 'save_post_custombox' ) ;
wp_create_nonce, wp_verify_nonce はクロスサイトリクエストフォージェリー対策。
アクセシビリティのため、class=”screen-reader-text” を入れている。
画面表示で複数行になっている部分があるが、括弧またはセミコロン以外の所の改行はソース上では改行ではない。
カスタムフィールドを利用したサイト例は、京都駅から がある。(サイト閲覧者からは、カスタムフィールド利用については判別できない)