register_and_do_post_meta_boxes()


WordPress関数register_and_do_post_meta_boxes()は、投稿編集画面にメタボックスを登録し、表示するために使用されます。この関数は主にプラグインやテーマ開発で利用されます。

構文

register_and_do_post_meta_boxes( string $post_type, string $context, WP_Post $post );

引数の説明:

  • $post_type (string) — メタボックスを追加する投稿タイプ
  • $context (string) — メタボックスの表示位置(normal, side, advanced)
  • $post (WP_Post) — 現在の投稿オブジェクト

例1: 基本的なメタボックスの登録

投稿編集画面にシンプルなメタボックスを追加します。

add_action('add_meta_boxes', function() { register_and_do_post_meta_boxes('post', 'normal', get_post()); });

例2: カスタム投稿タイプへの適用

カスタム投稿タイプ「product」にメタボックスを追加します。

add_action('add_meta_boxes', function() { register_and_do_post_meta_boxes('product', 'side', get_post()); });

例3: 複数のコンテキストでの使用

異なる表示位置にメタボックスを登録します。

add_action('add_meta_boxes', function() { register_and_do_post_meta_boxes('page', 'advanced', get_post()); });

例4: 特定の投稿IDに対して実行

特定の投稿に対してのみメタボックスを表示します。

if(get_the_ID() === 10) { register_and_do_post_meta_boxes('post', 'normal', get_post(10)); }

例5: カスタムコールバック関数との連携

カスタム関数と組み合わせて使用します。

function custom_meta_box() { echo 'カスタムコンテンツ'; } add_action('add_meta_boxes', function() { register_and_do_post_meta_boxes('post', 'normal', get_post()); });

例6: 複数の投稿タイプに一度に適用

配列を使用して複数の投稿タイプにメタボックスを登録します。

foreach(['post','page'] as $type) { register_and_do_post_meta_boxes($type, 'side', get_post()); }

例7: 条件付きでメタボックスを表示

特定の条件下でのみメタボックスを表示します。

if(current_user_can('edit_posts')) { register_and_do_post_meta_boxes('post', 'normal', get_post()); }

注意点

  • この関数は管理画面でのみ動作します
  • 適切なフック(add_meta_boxes)内で使用する必要があります
  • セキュリティ対策としてnonceフィールドの追加を検討してください

関連機能: