概要
get_post_custom
関数は、カスタムフィールド情報をすべて取得するために使用されます。この関数は、投稿やページに関連付けられたカスタムフィールドを簡単に取得し、アクセスする際に便利です。主に以下のような機能を実装する際に役立ちます。
- 投稿に付随する追加情報の取得
- カスタムフィールドを使用したデータの表示
- 特定の条件に基づくカスタムデータのフィルタリング
- ユーザーの入力データを保存・表示する際に利用
- テーマやプラグインの設定情報の管理
- サイトのカスタマイズにおけるデータの一元管理
- プロダクトやサービス情報の拡張表示
- ダイナミックなコンテンツ生成のサポート
構文
array get_post_custom( int $post_id = 0 )
パラメータ
$post_id
(int) – 投稿のID。指定しない場合は、グローバルな$post
変数から取得。
戻り値
- (array) – 指定した投稿に関連するカスタムフィールドの配列。
関連する関数
使用可能なバージョン
- WordPress 非推奨・削除バージョン: 特になし
コアファイルのパス
wp-includes/post.php
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | 〇 |
register_sidebar | |
wp_loaded | 〇 |
send_headers | |
parse_query | |
pre_get_posts | |
wp | 〇 |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプルコード 1
$post_id = get_the_ID();
$custom_fields = get_post_custom($post_id);
print_r($custom_fields);
このコードは、現在の投稿のカスタムフィールドを取得し、その内容を配列として表示します。
サンプルコード 2
$post_id = 123; // 投稿IDを指定
$custom_field_value = get_post_custom($post_id);
if (isset($custom_field_value['custom_field_name'])) {
echo $custom_field_value['custom_field_name'][0];
}
指定した投稿IDのカスタムフィールドから特定の値を表示するサンプルです。
サンプルコード 3
global $post;
$custom_fields = get_post_custom($post->ID);
foreach ($custom_fields as $key => $value) {
echo $key . ': ' . implode(', ', $value) . '<br>';
}
現在の投稿に関連する全てのカスタムフィールドキーとその値を表示するサンプルです。
サンプルコード 4
function display_custom_fields() {
global $post;
$custom_fields = get_post_custom($post->ID);
if (!empty($custom_fields)) {
foreach ($custom_fields as $key => $value) {
echo '<p>' . esc_html($key) . ': ' . esc_html($value[0]) . '</p>';
}
}
}
add_action('the_content', 'display_custom_fields');
投稿のコンテンツにカスタムフィールド情報を追加表示するためのサンプルです。
サンプルコード 5
function get_multiple_custom_fields($post_id) {
$custom_fields = get_post_custom($post_id);
return isset($custom_fields['another_field']) ? $custom_fields['another_field'][0] : null;
}
指定した投稿IDから別のカスタムフィールドの値を取得するための関数を定義しています。