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

概要

woocommerce_top_rated_products_widget_argsは、WooCommerceのトップ評価の商品ウィジェットを表示する際の引数をフィルタリングするためのフックです。このフィルタは、ウィジェットの表示に関わる様々な設定をカスタマイズするために利用されます。具体的には、表示する商品の数や並び順、カテゴリーの指定、出力される商品の属性などを変更することができます。

このフィルタを使うことで、以下のような機能の実装がよく行われます:

  1. 表示するトップ評価商品の数の変更
  2. カテゴリー別にトップ評価商品を表示
  3. 商品の評価基準をカスタマイズ
  4. 商品のソート順を変更
  5. 必要に応じて特定の属性を持つ商品のみを表示
  6. カスタムウィジェット領域でのトップ評価商品の表示

構文

add_filter('woocommerce_top_rated_products_widget_args', 'your_function_name');

パラメータ

  • $args (array): ウィジェットに渡される引数の配列。

戻り値

  • array: 修正された引数の配列。

使用可能なプラグインWooCommerceのバージョン

  • WooCommerce 2.1.0以降

ワードプレスのバージョン

  • WordPress 4.0以降

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

アクション 使用可能性
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_top_rated_products_widget_args', 'custom_top_rated_products_args');

function custom_top_rated_products_args($args) {
    $args['posts_per_page'] = 5; // 表示する商品の数を5に設定
    return $args;
}

このコードは、トップ評価商品ウィジェットが表示する商品の数を5に設定します。

サンプルコード2

add_filter('woocommerce_top_rated_products_widget_args', 'custom_top_rated_categories');

function custom_top_rated_categories($args) {
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => 'your-category-slug'
        )
    );
    return $args;
}

このコードは、特定のカテゴリー(スラッグで指定された)内のトップ評価商品だけを取得するようにウィジェットの引数を変更します。

サンプルコード3

add_filter('woocommerce_top_rated_products_widget_args', 'change_orderby');

function change_orderby($args) {
    $args['orderby'] = 'date'; // 商品を新しい順にソート
    return $args;
}

このコードは、トップ評価商品を表示する際に、新しい順でソートするように変更します。

サンプルコード4

add_filter('woocommerce_top_rated_products_widget_args', 'show_only_in_stock');

function show_only_in_stock($args) {
    $args['meta_query'] = array(
        array(
            'key' => '_stock_status',
            'value' => 'instock',
        )
    );
    return $args;
}

このコードは、在庫がある商品だけを表示するように引数を設定します。

サンプルコード5

add_filter('woocommerce_top_rated_products_widget_args', 'filter_by_custom_meta');

function filter_by_custom_meta($args) {
    $args['meta_query'] = array(
        array(
            'key' => 'custom_meta_key',
            'value' => 'custom_value',
            'compare' => '='
        )
    );
    return $args;
}

このコードは、カスタムメタデータによってフィルタリングされた商品だけを表示するように引数を変更します。

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


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