3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPress: Advanced Custom Fieldで作ったフィールドをまとめて取得

Last updated at Posted at 2015-02-06

例:ACFで作成したフィールドグループ

  • Name: text
  • Age: number
  • Sex: text

みたいなデータを作ったとする。
Name: Taro, Age: 20, Sex: Male
Name: Jiro, Age: 18, Sex: Male

index.php
<?php
// 配列作成
$entries = array();
// クエリのパラメータ
$args = array( 'posts_per_page' => -1, 'post_limits' => -1, 'post_type' => 'post', 'orderby' => 'ID', 'post_status' => 'publish' );
// WP_Queryを作成
$wp_query = new WP_Query( $args );
// 投稿の数だけループ
while($wp_query->have_posts()) : $wp_query -> the_post();

// 配列作成
$ary = array();

// カスタムフィールドの一覧をループさせる
foreach( get_post_custom_keys() as $cf_name ){
    // アンスコで始まるKeyがあるのでそれを省く
    if( !preg_match('/^_/', $cf_name ) ){
        // 配列に入れ込む
        $ary[$cf_name] = get_field( $cf_name );
    }
}
// 2次元配列にする
array_push( $entries, $ary );

endwhile;
?>

printするとこうなる。

index.html
Array
(
    [0] => Array
        (
            [Name] => Taro
            [Age] => 20
            [Sex] => Male
        )
    [1] => Array
        (
            [Name] => Jiro
            [Age] => 18
            [Sex] => Male
        )
)	

使用頻度は極めて低いですが、
JSONとかで一部のカスタム投稿とかを外に出したい時とかに使える気がします。
あとRepeaterでも使えると思います。

functions.php
// 記事保存時に実行
function generate_json( $data, $postarr ) {

// ここに上記の処理とか追加してJSONで出力したり?

}
add_filter( 'wp_insert_post_data'  , 'generate_json' , 99 , 2 );
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?