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

概要

woocommerce_get_stock_htmlフィルタは、WooCommerceの製品在庫状況を表示する際に使用されるフックです。このフィルタを使うことで、在庫情報の表示内容をカスタマイズしたり、特定の条件に基づいて動的に変更することができます。以下のような機能を実装する際に使用されることが一般的です。

  1. 在庫状況のカスタムメッセージを表示
  2. インベントリの残量に合わせて表示を変更
  3. 特定の製品カテゴリに対する在庫表示のスタイルを変更
  4. テーマに基づいて異なる在庫情報を提供
  5. 在庫が少ない場合のアラート表示
  6. ショッピングカートのステータスに応じた在庫情報の変更

構文

add_filter( 'woocommerce_get_stock_html', 'custom_stock_html', 10, 2 );

パラメータ

  • $html(string): デフォルトの在庫HTMLを含む文字列。
  • $product(WC_Product): 対象の製品オブジェクト。

戻り値

  • string: フィルタリングされた在庫HTMLを返す。

WooCommerce と WordPress のバージョン

  • 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_get_stock_html', 'custom_in_stock_message', 10, 2 );

function custom_in_stock_message( $html, $product ) {
    if ( $product->is_in_stock() ) {
        return '<span class="custom-stock-message">在庫あり!お早めに!</span>';
    }
    return $html;
}

説明: 在庫がある場合、カスタムメッセージを表示します。このコードは通常の在庫メッセージを上書きします。

サンプルコード 2: 在庫が少ない場合のメッセージ

add_filter( 'woocommerce_get_stock_html', 'low_stock_alert', 10, 2 );

function low_stock_alert( $html, $product ) {
    if ( $product->get_stock_quantity() < 5 ) {
        return '<span class="low-stock-warning">残りわずか!</span>';
    }
    return $html;
}

説明: 在庫が5未満の場合、警告メッセージを表示します。

サンプルコード 3: 特定の製品にメッセージを追加

add_filter( 'woocommerce_get_stock_html', 'custom_message_specific_product', 10, 2 );

function custom_message_specific_product( $html, $product ) {
    if ( $product->get_id() === 123 ) { // 製品IDが123の場合
        return '<span class="special-note">特別割引中!</span>' . $html;
    }
    return $html;
}

説明: 製品IDが123の場合のみ、特別なメッセージを追加します。

サンプルコード 4: CSSクラスの追加

add_filter( 'woocommerce_get_stock_html', 'add_custom_class_to_stock_html', 10, 2 );

function add_custom_class_to_stock_html( $html, $product ) {
    return '<div class="custom-stock-class">' . $html . '</div>';
}

説明: 在庫HTMLをラップしてカスタムCSSクラスを追加します。

サンプルコード 5: 在庫がない商品のメッセージ変更

add_filter( 'woocommerce_get_stock_html', 'out_of_stock_message', 10, 2 );

function out_of_stock_message( $html, $product ) {
    if ( $product->is_out_of_stock() ) {
        return '<span class="out-of-stock">売り切れ</span>';
    }
    return $html;
}

説明: 在庫がない商品の場合に、特定のメッセージを表示します。

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


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