WordPress - 2020-06-12

WooCommerceを自作テーマに実装した際に商品を並び替える方法

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; ?>
Related Posts

Related Posts

Wordpressの管理画面の投稿一覧カスタマイズ方法

2019-08-30

YouTube APIを使って視聴数ランキングを表示する(PHP)

2018-04-25

カスタム投稿を追加する方法-WordPress

2019-09-04

WordPressの検索結果から特定の情報を除外、または追加する方法

2019-09-03