get_post_custom()


WordPressのget_post_custom()関数は、投稿またはページのカスタムフィールドのデータを取得するために使用されます。

シンタックス

get_post_custom();

この関数は指定された投稿のカスタムフィールドを連想配列の形で返します。カスタムフィールドが存在しない場合は空の配列を返します。

戻り値

  • array — カスタムフィールドの配列。

例1: 現在の投稿のカスタムフィールドを取得する

現在の投稿のカスタムフィールドを取得し、配列として出力します。

<?php
$custom_fields = get_post_custom();
print_r( $custom_fields );
?>

例2: 特定のカスタムフィールドの値を取得する

特定の投稿IDのカスタムフィールドを取得し、特定のキーの値を表示します。

<?php
$custom_fields = get_post_custom( get_the_ID() );
if ( isset( $custom_fields['custom_key'] ) ) {
    echo $custom_fields['custom_key'][0];
}
?>

例3: すべてのカスタムフィールドをループで表示する

現在の投稿のカスタムフィールドをループして表示します。

<?php
$custom_fields = get_post_custom();
foreach ( $custom_fields as $key => $value ) {
    echo '<p>' . $key . ': ' . $value[0] . '</p>';
}
?>

例4: 投稿IDを指定してカスタムフィールドを取得する

別の投稿IDのカスタムフィールドを取得し、キーと値を出力します。

<?php
$custom_fields = get_post_custom( 42 );
foreach ( $custom_fields as $key => $value ) {
    echo '<p>' . $key . ': ' . $value[0] . '</p>';
}
?>

例5: カスタムフィールドが存在するか確認する

特定のカスタムフィールドが存在するかどうかを確認します。

<?php
$custom_fields = get_post_custom();
if ( isset( $custom_fields['custom_key'] ) ) {
    echo 'カスタムフィールドは存在します。';
} else {
    echo 'カスタムフィールドは存在しません。';
}
?>

注意事項

  • get_post_custom()関数はすべてのカスタムフィールドを取得するため、データ量が多い場合はパフォーマンスに注意が必要です。
  • カスタムフィールドの値は配列として返されるため、値を取得する際にはインデックス[0]を使用することを忘れないでください。

関連機能: