カスタム分類(タクソノミー)で実現する方法:
テーマの functions.php に以下を追加。
add_action( 'init', 'my_init', 0 );
function my_init() {
if ( ! is_taxonomy( 'genre' ) ) {
register_taxonomy(
'genre',
'post',
array( 'label' => 'ジャンル', 'show_ui' => false )
);
}
if ( ! term_exists( 'chinese', 'genre' ) )
wp_insert_term( '中華', 'genre', array( 'slug' => 'chinese' ) );
if ( ! term_exists( 'japanese', 'genre' ) )
wp_insert_term( '和食', 'genre', array( 'slug' => 'japanese' ) );
if ( ! term_exists( 'western', 'genre' ) )
wp_insert_term( '洋食', 'genre', array( 'slug' => 'western' ) );
if ( ! is_taxonomy( 'area' ) ) {
register_taxonomy(
'area',
'post',
array( 'label' => '地区', 'show_ui' => false )
);
}
if ( ! term_exists( 'north', 'area' ) )
wp_insert_term( '北区', 'area', array( 'slug' => 'north' ) );
if ( ! term_exists( 'south', 'area' ) )
wp_insert_term( '南区', 'area', array( 'slug' => 'south' ) );
if ( ! term_exists( 'west', 'area' ) )
wp_insert_term( '西区', 'area', array( 'slug' => 'west' ) );
if ( ! term_exists( 'east', 'area' ) )
wp_insert_term( '東区', 'area', array( 'slug' => 'east' ) );
}
//
add_action( 'admin_menu', 'my_tax_box' );
function my_tax_box() {
remove_meta_box( 'tagsdiv-genre', 'post', 'core' );
remove_meta_box( 'tagsdiv-area' , 'post', 'core' );
add_meta_box( 'my_tax', '選択してください', 'my_tax_html', 'post', 'side', 'core');
}
//
function my_tax_html( $post, $box ) {
echo '<input type="hidden" name="my_tax_nonce" id="my_tax_nonce" value="'
. wp_create_nonce( 'my_tax' ) . '" />';
my_tax_html_by_tax( $post, 'genre' );
my_tax_html_by_tax( $post, 'area' );
}
function my_tax_html_by_tax( $post, $tax ) {
echo '<div>' . get_taxonomy( $tax )->label . ':</div>';
$terms = get_terms( $tax, 'hide_empty=0' );
$selected_terms = wp_get_object_terms( $post->ID, $tax );
$selected_term = empty( $selected_terms ) ? '' : ( $selected_terms[0]->slug );
foreach ( $terms as $term ) {
echo '<p><input type="radio" name="my_' . $tax
. '" id="my_' . esc_attr( $term->slug )
. '" value="' . esc_attr( $term->slug )
. '"' . checked( $selected_term, $term->slug, false )
. '/>' . esc_html( $term->name ) . "</p>\n";
}
}
//
add_action( 'save_post', 'my_tax_update', 10, 2 );
function my_tax_update( $post_id, $post ) {
if ( ! wp_verify_nonce( $_POST['my_tax_nonce'], 'my_tax' ) ) {
return;
}
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
if( 'post' == $_POST['post_type'] ) {
if( ! current_user_can( 'edit_post', $post_id ) )
return;
}else{
return;
}
$val = trim( $_POST['my_genre'] );
if ( '' != $val )
wp_set_object_terms( $post_id, $val, 'genre' );
$val = trim( $_POST['my_area'] );
if ( '' != $val )
wp_set_object_terms( $post_id, $val, 'area' );
}
ジャンル・地区の表示(例)。
the_post();
$genre = array_pop( get_the_terms( 0, 'genre' ) );
$area = array_pop( get_the_terms( 0, 'area' ) );
echo '<p>genre=' . esc_html( $genre->name ) . '</p>';
echo '<p>area =' . esc_html( $area->name ) . '</p>';