WordPressのカスタムフィールドを使って商品を価格順(数字順)に並べ替える(ソートする)方法
例:
カスタム投稿タイプ: product
カスタムフィールド名: price
カスタムフィールドの値: 1000 (ex.数字)
<?php $args = array( 'post_type' => 'product',// 投稿タイプ 'meta_key' => 'price',// カスタムフィールド名 'orderby' => 'meta_value_num',// 数字で並べ替え 'order' => 'ASC',// 数字が小さい→大きい順(昇順)、降順はDESC ); $the_query = new WP_Query( $args ); ?> <?php if ( $the_query->have_posts() ) : ?> <!-- pagination here --> <!-- the loop --> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <h2><?php the_title(); ?></h2> <?php endwhile; ?> <!-- end of the loop --> <!-- pagination here --> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?>
価格(数字)を絞り込みたい場合
カスタムフィールドの数字(価格など)で投稿を絞り込みたい場合。
例:投稿ページのカスタムフィールドkey=price、値=500以上を表示
$args = array( 'post_type' => 'post', 'meta_query' => array( array( 'key'=>'price', 'value'=>'500', 'compare'=>'>',//500より大きい 'type'=>'NUMERIC' ) ), 'orderby' => 'meta_value_num', 'order' => 'ASC' ); $the_query = new WP_Query( $args ); }
値の絞り込み(条件指定)
'compare'=>'>',//500より大きい 'compare'=>'>=',//500以上 'compare'=>'<',//500より小さい 'compare'=>'<=',//500以下 //▲▲円〜××円の間 array( 'key' => 'price', 'value' => array(500,1000) 'compare' => 'BETWEEN' )