WooCommerceを自作テーマに実装した際に商品を並び替える方法をまとめました。
新着順の場合
<?php
$args = array(
'post_status' => 'publish',
'post_type' => 'product',
'posts_per_page' => 4,
'orderby' => 'date',
'order' => 'DESC',
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
//ループさせたい処理
endwhile;
else:
//記事がない場合の処理
endif; ?>
人気順の場合
<?php
$args = array(
'post_status' => 'publish',
'post_type' => 'product',
'posts_per_page' => 5,
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_key' => 'total_sales',
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
//ループさせたい処理
endwhile;
else:
//記事がない場合の処理
endif; ?>
価格順(高い)の場合
<?php
$args = array(
'post_status' => 'publish',
'post_type' => 'product',
'posts_per_page' => 5,
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_key' => '_price',
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
//ループさせたい処理
endwhile;
else:
//記事がない場合の処理
endif; ?>
価格順(安い)の場合
<?php
$args = array(
'post_status' => 'publish',
'post_type' => 'product',
'posts_per_page' => 5,
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_key' => '_price',
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
//ループさせたい処理
endwhile;
else:
//記事がない場合の処理
endif; ?>