Skip to content

Instantly share code, notes, and snippets.

@Hiroki-Kawakami
Last active January 4, 2024 11:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hiroki-Kawakami/38701210f32c2bf73d81d274bfce68cb to your computer and use it in GitHub Desktop.
Save Hiroki-Kawakami/38701210f32c2bf73d81d274bfce68cb to your computer and use it in GitHub Desktop.
投稿に画像を扱うカスタムフィールドを追加するサンプルプラグイン

imagefield

カスタムフィールドで画像を記事末尾に追加するプラグイン。 以下の記事のサンプルコード

[Wordpress]メディアライブラリから画像を選べるカスタムフィールドを作成する

imagefield.phpimagefield.jswp-content/plugins/imagefield/内に配置し、プラグインを有効化して使用する。

  • Step1 カスタムフィールドを作成する ※ここまで
  • Step2 画像のIDを扱う
  • Step3 カスタムフィールドの見た目を調整する
  • Step4 複数の画像に対応する
// まだ使わない
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment