0
1

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.

Wordpress5 カスタムフィールの作成とテンプレートでの表示方法

Posted at

Wordpress5のカスタムフィールドの作り方

Wordpress5からカスタムフィールドは右上の設定アイコンから表示できるようになった。チェックを入れ、「有効化してリロード」ボタンを押せば表示されるようになる。

custom-field-1.png

カスタムフィールドは投稿画面の下で作成する。フィールド名を記入し、値を入れるだけでOK。

custom-field-2.png

次からは選択フォームに以前作成したカスタムフィールドが表示されるので、それを選択する。

カスタムフィールドの値を表示する方法

一覧ページや記事ページの表示したい場所にコードを追加するだけ。

echo get_post_meta($post->ID, 'key', true);

テンプレートに追記する場合はこんな感じ。

<div class="entry-meta">
  <ul class="nav">
    <li>投稿日: <?php echo get_the_date('Y-m-d'); ?></li>
    <li>サイズ: <?php echo get_post_meta($post->ID, 'size', true); ?></li>
  </ul>
</div><!-- .entry-meta -->

1つのカスタムフィールドで複数の値を入力した場合の表示方法

1つのカスタムフィールド名(キー)に対して複数の値を入れる場合は、必要な分だけキーを追加して1つづつ値を入れていく。

custom-field-3.png

値の表示方法は配列の表示と同じ。

<?php
$colors = get_post_meta($post->ID, 'color', false);
if( count( $colors ) != 0 ) { ?>

<ul>
  <?php foreach($colors as $color) {
    echo '<li>'.$color.'</li>';
  }
  ?>
</ul>

<?php } ?>
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?