WordPress Tips

Advanced Custom Fieldsの値でソートする

Advanced Custom Fieldsの値でソートする

タイトルの通り、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/

今月キャンペーン特典があるサービス

  • エックスサーバー
    月額費用が最大35%キャッシュバックの693円&ドメイン永久無料 - 2023年6月9日(金)12:00まで
  • ConoHa WING
    WINGパック36ヶ月で月額687円 52%OFF - 2023年6月13日(火)16:00まで
  • カラフルボックス
    .jp取り扱いスタート。BOX2以上の月額費用が25%OFFのクーポンコード「SERVER25

-WordPress Tips
-