WordPressでカスタムフィールドで選択した記事を表示させる

WordPress

要件

カスタム投稿とカスタムフィールドで特定の記事をユーザー側で簡単に選択できるようにして、それをスライダーに追加したり、関連記事として表示させる場合の実装方法。

カスタム投稿とカスタムフィールドの設定

カスタム投稿を作成して、その中にカスタムフィールドを表示させる。

カスタムフィールドの内容は、フィールドタイプは「投稿オブジェクト」、戻り値の形式は「投稿ID」をしていする。他の項目は任意でOK。

指定した投稿の取得、表示

カスタムフィールドの値を取得する

カスタムフィールド一つに複数の投稿が有る場合

$post_id_array = get_field('relation_post'); で投稿 id を取得できる。

それをループに入れて サブクエリを回せば指定した投稿を取得、表示できる

 <?php
   $relations_args_in_custom_field = [
   'post_type' => 'post',
   'post__in' => $post_id_array
    ];
   $relations_query_in_custom_field = new WP_Query($relations_args_in_custom_field);
   if ($relations_query_in_custom_field->have_posts()) :
   while ($relations_query_in_custom_field->have_posts()) : $relations_query_in_custom_field->the_post();
   $cat = get_the_category();
   $cat = $cat[0];
  ?>
    <li class="item">
     <article class="rticle">
       <a href="<?php the_permalink(); ?>">
          <figure class="img">
            <?php the_post_thumbnail() ?>
          </figure>
          <div class="textWrapper">
             <h3 class="articleTitle"><?php the_title(); ?></h3>
             <div class="articleFooter">
               <time class="time relationPost__time">
                 <?php echo the_date('Y.n.j H:i:s'); ?>
               </time>
               <span class="__category subEn-font"><?php echo $cat->cat_name; ?></span>
             </div>
          </div>
        </a>
      </article>
     </li>
    <?php
     wp_reset_postdata();
    endwhile;
      endif;
      ?>

複数のカスタムフィールドへ選択した投稿が分かれている場合(スライダーなど表示順をCMSしたい場合)

forの部分は、カスタムフィールドの数をいれてください。

$post_id = get_field('features_content' . $i, 2148);の部分は第一引数へカスタムフィールドの名前をいれてください。

今回の場合は、features_content1 features_content2 …というような連番になっています。

というか、連番にしないと面倒です。(カスタムフィールドの設定時に連番にしておきましょう)

<?php
$post_id_array = array();
for ($i = 1; $i < 11; $i++) {
  $post_id = get_field('features_content' . $i, 2148);
  if ($post_id !== false) {
    array_push($post_id_array, $post_id);
  }
}
$features_args = [
  'post_type' => 'post',
  'post__in' => $post_id_array
];
$features_query = new WP_Query($features_args); ?>
<?php if ($features_query->have_posts()) :?>
<?php while ($features_query->have_posts()) : $features_query->the_post(); ?>
 <li class="item">
     <article class="rticle">
       <a href="<?php the_permalink(); ?>">
          <figure class="img">
            <?php the_post_thumbnail() ?>
          </figure>
          <div class="textWrapper">
             <h3 class="articleTitle"><?php the_title(); ?></h3>
             <div class="articleFooter">
               <time class="time relationPost__time">
                 <?php echo the_date('Y.n.j H:i:s'); ?>
               </time>
               <span class="__category subEn-font"><?php echo $cat->cat_name; ?></span>
             </div>
          </div>
        </a>
      </article>
     </li>
    <?php
     wp_reset_postdata();
    endwhile;
      endif;
      ?>
タイトルとURLをコピーしました