|
<?php |
|
/* |
|
Plugin Name: Image Custom Field Sample |
|
Description: 投稿に画像を扱うカスタムフィールドを追加するサンプルプラグイン |
|
Author: Hiroki Kawakami |
|
Version: 0.1 |
|
Author URI: https://ideal-reality.com |
|
*/ |
|
|
|
// 編集画面にカスタムフィールドの表示領域を追加する |
|
add_action('admin_menu', 'add_image_custom_field'); |
|
function add_image_custom_field() { |
|
add_meta_box( |
|
'imagefield_block', // 編集画面セクションのHTML要素のID |
|
'Imagefield', // 編集画面セクションのタイトル |
|
'insert_imagefield', // 編集画面セクションにHTML出力する関数 |
|
'post', // 投稿タイプ |
|
'normal' // 編集画面セクションが表示される部分 |
|
); |
|
} |
|
|
|
// 編集画面の表示領域に使用されるHTML |
|
function insert_imagefield() { |
|
global $post; |
|
$imagefield = get_post_meta($post->ID, 'imagefield', true); ?> |
|
<div> |
|
<input type="text" name="imagefield" id="imagefield_input" value="<?php echo $imagefield; ?>"/> |
|
</div> |
|
<?php } |
|
|
|
// カスタムフィールドの値を保存する処理 |
|
add_action('save_post', 'save_imagefield'); |
|
function save_imagefield($post_id) { |
|
if(isset($_POST['imagefield'])){ |
|
update_post_meta($post_id, 'imagefield', $_POST['imagefield']); |
|
} else { |
|
delete_post_meta($post_id, 'imagefield'); |
|
} |
|
} |
|
|
|
// 投稿内容の末尾にカスタムフィールドの内容を追加 |
|
add_filter('the_content', 'add_imagefield_content', 1); |
|
function add_imagefield_content($content) { |
|
if ($text = get_post_meta(get_the_ID(), 'imagefield', true)) { |
|
$content .= '<h2>Imagefield</h2>'; |
|
$content .= '<p>' . $text . '</p>'; |
|
} |
|
return $content; |
|
} |