概要
woocommerce_stock_html
フィルタは、WooCommerce商品ページにおける在庫状況を表示する際のHTMLをカスタマイズするためのフックです。このフィルタを使用することで、デフォルトの在庫情報表示を変更し、自分のニーズに合わせた形で在庫情報を出力することができます。以下のような場面でよく使われます:
- 在庫情報のフォーマットを変更する
- 在庫状況に応じたカスタムメッセージを追加する
- 在庫が少ない商品に警告デザインを適用する
- 在庫のテキストを多言語対応にする
- 販売中の商品の情報を強調する
- 在庫状況に基づいたアイコンを追加する
構文
add_filter('woocommerce_stock_html', 'custom_stock_html', 10, 2);
パラメータ
$html
(string): 既存の在庫HTML$product
(WC_Product): 対象の商品オブジェクト
戻り値
- (string): カスタマイズされた在庫HTML
使用可能なバージョン
- WooCommerce: バージョン3.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_stock_html', 'custom_stock_message', 10, 2);
function custom_stock_message($html, $product) {
if ($product->is_in_stock()) {
$html .= '<p>この商品は在庫があります!</p>';
} else {
$html .= '<p>残念ながら、この商品は在庫切れです。</p>';
}
return $html;
}
説明: 在庫状況に応じてカスタムメッセージを追加する例です。
サンプルコード2: 在庫が少ない商品の警告デザイン
add_filter('woocommerce_stock_html', 'low_stock_warning', 10, 2);
function low_stock_warning($html, $product) {
if ($product->get_stock_quantity() < 5 && $product->is_in_stock()) {
$html .= '<span style="color: red;">注意:在庫が少なくなっています!</span>';
}
return $html;
}
説明: 在庫が少ない場合に警告メッセージを表示するスタイルを適用する例です。
サンプルコード3: 多言語対応の在庫テキスト
add_filter('woocommerce_stock_html', 'multilingual_stock_text', 10, 2);
function multilingual_stock_text($html, $product) {
$in_stock_text = __('在庫あり', 'text-domain');
if ($product->is_in_stock()) {
$html = str_replace('在庫あり', $in_stock_text, $html);
}
return $html;
}
説明: 在庫があるテキストを多言語対応にするため、翻訳機能を使った例です。
サンプルコード4: アイコンの追加
add_filter('woocommerce_stock_html', 'add_stock_icon', 10, 2);
function add_stock_icon($html, $product) {
if ($product->is_in_stock()) {
$icon = '<img src="path/to/icon.png" alt="In Stock" />';
$html = $icon . $html;
}
return $html;
}
説明: 在庫がある場合にアイコンを表示する例です。
サンプルコード5: 在庫状況による表示内容のコントロール
add_filter('woocommerce_stock_html', 'dynamic_stock_content', 10, 2);
function dynamic_stock_content($html, $product) {
if ($product->is_in_stock() && $product->get_stock_quantity() > 10) {
$html .= '<p>大量入荷中!</p>';
} elseif (!$product->is_in_stock()) {
$html .= '<p>次回の入荷をお待ちください。</p>';
}
return $html;
}
説明: 在庫数に応じて異なるメッセージを表示するロジックの例です。
これらのサンプルコードはすべて著作権フリーのものであり、WooCommerceの拡張やカスタマイズに役立つものです。