LoginSignup
4
1

More than 3 years have passed since last update.

WPのカスタムフィールドにJSON形式のテキストを入れて出力

Last updated at Posted at 2020-04-03

経緯

他のCMSを使った時に、1つのカスタムフィールドで複数のデータを扱うことがあったので、WPでも作ってみようと思いました。

プラグイン

カスタムフィールドの追加は「Advanced Custom Fields」を使いました。
img01.jpg

フィールドに入れる。

↓これを

name.json
[
    {
        "id":"1",
        "first_name":"佐藤",
        "last_name":"太郎"
    },
    {
        "id":"2",
        "first_name":"鈴木",
        "last_name":"次郎"
    }
]

↓ポン

スクリーンショット 2020-04-03 16.23.23.png

ソース

フィールドラベルは、「name」としました。

single.php
<?php

while ( have_posts() ) :
    the_post();

    // カスタムフィールドを取得
    $area = get_field('name');
    // JSON($json)を連想配列に変換(デコード)する
    $json = json_decode( $area , true ) ;
    $cnt = count($json);
    for ($i = 0; $i <= $cnt - 1; $i++) {
        ?>
            <p>id:<?php echo $json[$i]['id']; ?></p>
            <p>名字:<? echo $json[$i]['first_name']; ?></p>
            <p>名前:<? echo $json[$i]['last_name']; ?></p>
        <?php
    }

endwhile; // End of the loop.
?>

保存!

でけた

スクリーンショット 2020-04-03 16.18.25.png

管理画面側の見た目をもっと整えれれば使い勝手よさそう。

4
1
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
4
1