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

概要

woocommerce_product_get_rating_html フィルタは、WooCommerce プラグイン内で製品の評価 HTML をカスタマイズするために使用されます。これにより、開発者は製品ページで表示される評価の見た目や内容を変更することができます。このフィルタは以下のような機能を実装する際によく使われます。

  1. 評価のスタイルをカスタマイズ
  2. カスタム評価システムの統合
  3. 評価の表示条件の変更
  4. SEO 向けのマークアップ調整
  5. 表示される星の数の変更
  6. 複数の評価基準の表示

構文

add_filter( 'woocommerce_product_get_rating_html', 'your_function_name', 10, 2 );

パラメータ

  • string $rating_html — デフォルトの評価 HTML。
  • WC_Product $product — 評価を取得する WooCommerce 製品オブジェクト。

戻り値

  • string — カスタマイズされた評価 HTML。

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

  • WooCommerce バージョン 3.0 以上。

WordPress のバージョン

  • 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_product_get_rating_html', 'custom_rating_html', 10, 2 );
function custom_rating_html( $rating_html, $product ) {
    return '<span class="custom-rating">⭐️⭐️⭐️⭐️⭐️</span>';
}

このサンプルコードは、すべての製品に対して固定の評価 HTML を ⭐️⭐️⭐️⭐️⭐️ で返します。

サンプルコード 2: 評価の数を変更

add_filter( 'woocommerce_product_get_rating_html', 'modify_rating_count', 10, 2 );
function modify_rating_count( $rating_html, $product ) {
    $new_rating = 4; // 例えば4つ星
    return str_replace( '★', '⭐', str_repeat( '★', $new_rating ) );
}

このコードでは、製品の評価を4つ星に変更します。

サンプルコード 3: 動的な評価の取得

add_filter( 'woocommerce_product_get_rating_html', 'dynamic_rating_html', 10, 2 );
function dynamic_rating_html( $rating_html, $product ) {
    $avg_rating = round( $product->get_average_rating() );
    return str_repeat( '★', $avg_rating );
}

このサンプルでは、製品の平均評価に基づいて評価の星を表示します。

サンプルコード 4: 評価にテキストを追加

add_filter( 'woocommerce_product_get_rating_html', 'add_text_to_rating', 10, 2 );
function add_text_to_rating( $rating_html, $product ) {
    return $rating_html . ' <span class="rating-text">(お客様の評価)</span>';
}

このコードにより、評価の隣に「お客様の評価」というテキストが追加されます。

サンプルコード 5: 特定のユーザーの評価に基づくカスタマイズ

add_filter( 'woocommerce_product_get_rating_html', 'conditional_rating_html', 10, 2 );
function conditional_rating_html( $rating_html, $product ) {
    if ( is_user_logged_in() ) {
        return '<span class="thank-you">ありがとう!あなたの評価が助けになっています。</span>';
    }
    return $rating_html;
}

このサンプルコードは、ユーザーがログインしている場合に特別なメッセージを表示します。

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


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