タイトルの通り、Wordpressの投稿記事やカスタム投稿タイプの記事をAdvanced custom fieldsで設定した値で並び替えしたいときのメモ。
カスタム投稿タイプ: events
ACFのフィールド名: event_date (日付)
get_postsを使う
$args = array(
'post_type' => 'events',
'numberposts' => -1,
'post_status' => 'publish',
'orderby' => 'meta_value',
'meta_key' => 'event_date', //ACFのフィールド名
'order' => 'DESC'
);
$posts = get_posts($args);
if( $posts ): ?>
<ul>
<?php foreach( $posts as $post ): setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?> (date: <?php the_field('event_date'); ?>)</a>
</li>
<?php endforeach;?>
</ul>
<?php wp_reset_postdata(); ?>
<?php endif; ?>WP_Queryを使う
カスタム投稿タイプ: event
ACFのフィールド名: featured(真偽値)
<?php $the_query = new WP_Query(array( 'post_type' => 'event', 'numberposts' => -1, 'meta_key' => 'featured', //ACFのフィールド名 'orderby' => 'meta_value', 'order' => 'DESC' )); ?> <?php if( $the_query->have_posts() ): ?> <ul> <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </li> <?php endwhile; ?> </ul> <?php endif; ?> <?php wp_reset_query(); ?>
Advanced Custom Fieldsのドキュメントに掲載されています。
https://www.advancedcustomfields.com/resources/orde-posts-by-custom-fields/
