WordPress Tips

Advanced Custom Fieldsの値でソートする

2017-10-25

本記事にはプロモーションが含まれています。

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/

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

  • エックスサーバー
    利用料最大30%キャッシュバッグ月額693円&ドメイン永久無料 - 2024年5月1日(水)12:00まで
  • ConoHa WING
    WINGパック36ヶ月で月額678円 53%OFF ドメイン2個無料 - 2024年4月19日(金)16:00まで
  • カラフルボックス
    ドメイン永久無料特典とBOX2以上の月額費用が50%OFFのクーポンコード「SERVER50

-WordPress Tips
-