プラグインWooCommerceのwoocommerce_get_catalog_ordering_argsフィルタの使用方法・解説

概要

woocommerce_get_catalog_ordering_args フィルタは、WooCommerceにおけるカタログの並び順に関連するクエリ引数を変更するために使用されます。このフィルタを利用することで、商品一覧の表示順序をカスタマイズしたり、新しい並び替え基準を追加したりすることが可能です。

よく使われる機能の例は以下の通りです。

  1. 商品の新着順の表示
  2. 人気商品の表示順の設定
  3. カスタム属性による商品並び替え
  4. セール商品を上位に表示
  5. カテゴリーごとの特定の商品グルーピング
  6. 特定の条件に基づくユーザー指定の並び替え

このフィルタは、WooCommerceのバージョン2.1以降、およびWordPressのバージョン4.0以降で利用可能です。

構文

add_filter( 'woocommerce_get_catalog_ordering_args', 'your_custom_function' );

パラメータ

  • $args : 商品の並び順を決定するための引数を含む配列。

戻り値

  • 変更された引数を含む配列。

この関数のアクションでの使用可能性

アクション 使用可能性
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプル1: 商品の新着順表示

このコードは、商品を新着順に表示するように並び替えの引数を設定します。

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_newness_product_order' );
function custom_newness_product_order( $args ) {
    $args['orderby'] = 'date';
    $args['order'] = 'DESC';
    return $args;
}

引用元: https://developer.woocommerce.com/

サンプル2: 人気商品の優先表示

このコードは、人気商品の並び順を優先して表示するように設定します。

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_popularity_order' );
function custom_popularity_order( $args ) {
    $args['orderby'] = 'meta_value_num';
    $args['meta_key'] = 'total_sales';
    $args['order'] = 'DESC';
    return $args;
}

引用元: https://developer.woocommerce.com/

サンプル3: 特定の属性による並び替え

このコードは、特定のカスタム属性に基づいて商品を並び替えます。

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_attribute_order' );
function custom_attribute_order( $args ) {
    $args['orderby'] = 'meta_value';
    $args['meta_key'] = 'custom_attribute';
    return $args;
}

引用元: https://developer.woocommerce.com/

サンプル4: セール商品の優先表示

このコードは、セール中の商品を上位に表示します。

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_sale_order' );
function custom_sale_order( $args ) {
    $args['orderby'] = 'meta_value';
    $args['meta_key'] = '_sale_price';
    return $args;
}

引用元: https://developer.woocommerce.com/

サンプル5: ユーザーの選択による並び替え

このコードは、ユーザーが選択した並び替えオプションに基づいて商品を並び替えます。

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_user_selected_order' );
function custom_user_selected_order( $args ) {
    if ( isset( $_GET['orderby'] ) ) {
        switch ( $_GET['orderby'] ) {
            case 'price':
                $args['orderby'] = 'meta_value_num';
                $args['meta_key'] = '_price';
                $args['order'] = 'ASC';
                break;
            // 他のケースも追加可能
        }
    }
    return $args;
}

引用元: https://developer.woocommerce.com/

この関数について質問する


上の計算式の答えを入力してください