ワードプレスのpost_custom関数の使用方法・解説

概要

post_custom関数は、特定の投稿のカスタムフィールドの値を取得するために使用されるWordPressの関数です。カスタムフィールドは、投稿やページに追加のメタデータを保存できる機能であり、様々な用途に利用されています。具体的には、以下のような機能を実装する際によく使われます。

  1. ソーシャルメディアシェアのリンク追加
  2. 投稿にカスタムグラフィックまたはアイコンの追加
  3. 商品ページに価格を表示
  4. 投稿の著者情報をカスタムフィールドから引き出す
  5. 特別なタグラインやサブタイトルの追加
  6. カスタムバナーリンクの表示
  7. 投稿ごとのカスタムスタイルの適用
  8. 詳細なSEOメタ情報の保存と表示

構文

string post_custom( $key, $post_id = null );

パラメータ

  • $key (string) : 取得したいカスタムフィールド名。
  • $post_id (int, optional) : 特定の投稿のID。指定しない場合は現在の投稿が使用されます。

戻り値

  • (string) : 指定されたカスタムフィールドの値。存在しない場合は空の文字列が返されます。

関連する関数

使用可能なバージョン

post_custom関数は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

$value = post_custom('custom_field_key');
echo esc_html($value);

このコードは、指定したカスタムフィールドcustom_field_keyの値を取得し、HTMLエスケープを施して表示します。

サンプルコード 2

if($custom_value = post_custom('featured_image_url')) {
    echo '<img src="'.esc_url($custom_value).'" alt="">';
}

このコードは、カスタムフィールドfeatured_image_urlから値を取得し、それが存在する場合は画像を表示します。

サンプルコード 3

$post_id = 42; // 取得する投稿IDを指定する
$subtitle = post_custom('post_subtitle', $post_id);
echo '<h2>' . esc_html($subtitle) . '</h2>';

このコードは、投稿IDが42の投稿からカスタムフィールドpost_subtitleを取得して表示します。

サンプルコード 4

$author_bio = post_custom('author_bio');
if(!empty($author_bio)) {
    echo '<div class="author-bio">'. esc_html($author_bio) .'</div>';
}

このコードは、author_bioカスタムフィールドから著者のバイオグラフィを取得し、存在すれば表示します。

サンプルコード 5

$price = post_custom('product_price');
echo '価格: ' . esc_html($price) . '円';

このコードは、product_priceカスタムフィールドから値を取得し、商品価格として表示します。

この関数について質問する


上の計算式の答えを入力してください