WordPress の投稿で全てのカスタムフィールドの値(隠し値含めて)を取得する方法

WordPress の投稿(ページやカスタム投稿タイプでも可)でカスタムフィールドのキーや値を全て取得するには get_post_custom() を使用します。この get_post_custom() については下記ページが参考になりました。

1
2
$custom = get_post_custom($post->ID);
print_r($custom);

試しにこのようなコードを書いて、記事のループ内に組み込むと、以下のように全てのカスタムフィールドが取得されます。_edit_last と _edit_lock は WordPress の記事にデフォルトで設定されている値です。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Array
(
    [_edit_last] => Array
        (
            [0] => 1
        )
 
    [_edit_lock] => Array
        (
            [0] => 1334031706:1
        )
 
    [test] => Array
        (
            [0] => これはテストフィールドです。
        )
 
    [test2] => Array
        (
            [0] => これはテストフィールド2です。
            [1] => これはテストフィールド2ですの2)
 
)

ちなみにこれは豆知識ですが、カスタムフィールドのキーは _edit_last や _edit_lock のようにアンダーラインを先頭に付けることで、WordPress の管理画面から見えなくすることができます。バックグラウンドで値を保存したい場合は活用しましょう。

蛇足

ちなみに get_post_custom() は以下のようになっていて、結果的には get_post_meta() を呼んでいるため、get_post_meta($post->ID) でも同じような値を取得することが可能です。このコードは wp-includes/post.php にありますので時間のある人は確認してみましょう。

1548
1549
1550
1551
1552
1553
1554
function get_post_custom( $post_id = 0 ) {
    $post_id = absint( $post_id );
    if ( ! $post_id )
        $post_id = get_the_ID();
 
    return get_post_meta( $post_id );
}

ただし、実際に取得をしようとすると下記のように(引数2にエラーがあるという)エラーメッセージが出てきますので、エラーを出さずに使う場合は get_post_meta($post->ID, ”) と引数2に空文字列を入れて取得をする必要がありますので注意してください。

Warning: Missing argument 2 for get_post_meta(), called in /var/www/localhost/demo/wp-content/plugins/delete-expired-custom-field.php on line 25 and defined in /var/www/localhost/demo/wp-includes/post.php on line 1465 Notice: Undefined variable: key in /var/www/localhost/demo/wp-includes/post.php on line 1466 Array ( [_edit_last] => Array ( [0] => 1 ) [_edit_lock] => Array ( [0] => 1334032186:1 ) [test] => Array ( [0] => これはテストフィールドです。 ) [test2] => Array ( [0] => これはテストフィールド2です。 [1] => これはテストフィールド2ですの2。 ) )

個人的には空文字列が入っていると、記載ミスみたいに見えてしまうので、get_post_custom() を使う方がスッキリしていて良さそうです。好みで変えてみましょう。

コメント

コメントは受け付けていません。