Created
August 24, 2012 08:30
-
-
Save s-hiroshi/3447490 to your computer and use it in GitHub Desktop.
WordPress >snippets > custom field on custom post type example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// カスタム投稿タイプ | |
function create_example(){ | |
$labels = array( | |
'name' => 'サンプル', | |
'singular_name' => 'サンプル', | |
'add_new' => 'サンプルを追加', | |
'add_new_item' => '新しいサンプルを追加', | |
'edit_item' => 'サンプルを編集', | |
'new_item' => '新しいサンプル', | |
'view_item' => 'サンプルを編集', | |
'search_items' => 'サンプルを探す', | |
'not_found' => 'サンプルはありません', | |
'not_found_in_trash' => 'ゴミ箱にサンプルはありません', | |
'parent_item_colon' => '' | |
); | |
$args = array( | |
'labels' => $labels, | |
'public' => true, | |
'capability_type' => 'post', | |
'hierarchical' => false, | |
'has_archive' => true, | |
'supports' => array( | |
'title', | |
'editor' | |
), | |
'register_meta_box_cb' => 'example_meta_box' // カスタムフィールド有効化 | |
); | |
register_post_type('example', $args); | |
} | |
// カスタムフィールド | |
function example_meta_box($post){ | |
add_meta_box( | |
'example_meta', | |
'設定欄', | |
'example_meta_callback', | |
'example', | |
'normal', | |
'high' | |
); | |
} | |
function example_meta_callback($post, $box){ | |
// カスタムフィールドの値を取得 | |
$field1 = get_post_meta($post->ID, 'field1', true); | |
$field2 = get_post_meta($post->ID, 'field2', true); | |
// | |
echo wp_nonce_field('example_meta', 'my_meta_nonce'); | |
// 入力域 | |
echo 'field1:<input type="text" name="field1" value="' . $field1 . '" /><br />'; | |
echo 'field2:<input type="text" name="field2" value="' . $field2 . '" />'; | |
} | |
// 保存処理 | |
add_action('save_post', 'example_meta_update'); | |
function example_meta_update($post_id){ | |
if (!wp_verify_nonce( $_POST['my_meta_nonce'], 'example_meta')) { | |
return $post_id; | |
} | |
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { | |
return $post_id; | |
} | |
if ('example' == $_POST['post_type']) { | |
if(!current_user_can('edit_post', $post_id)) { | |
return $post_id; | |
} | |
} else { | |
return $post_id; | |
} | |
$field1 = $_POST['field1']; | |
$field2 = $_POST['field2']; | |
if($field1 == '') { | |
delete_post_meta($post_id, 'field1'); | |
} | |
else { | |
update_post_meta($post_id, 'field1', $field1); | |
} | |
if($field2 == '') { | |
delete_post_meta($post_id, 'field2'); | |
} | |
else { | |
update_post_meta($post_id, 'field2', $field2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment