概要
woocommerce_format_stock_quantity
関数は、WooCommerce において在庫数量をフォーマットするために使用されます。この関数は、商品が在庫にある場合にその数量を表示し、在庫がない場合には適切なメッセージを表示します。主に以下のような機能を実装する際によく使われます。
- 商品ページでの在庫状況の表示
- カート内の商品在庫数の表示
- 商品リストやアーカイブページでの在庫数の表示
- 商品の詳細情報のカスタマイズ
- 在庫管理のためのカスタムフックの実装
- 在庫のあった場合とない場合でのメッセージの切り替え
構文
woocommerce_format_stock_quantity( $quantity, $product );
パラメータ
$quantity
(int) : 表示する在庫の数量。$product
(WC_Product) : WooCommerce 商品オブジェクト。
戻り値
- フォーマットされた在庫数量の文字列。
使用可能なプラグインのバージョン
- WooCommerce バージョン: 3.9 以降
使用可能な WordPress のバージョン
- WordPress バージョン: 5.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: 在庫数量の表示
$product = wc_get_product( $product_id );
$stock_quantity = $product->get_stock_quantity();
echo woocommerce_format_stock_quantity( $stock_quantity, $product );
このコードは、指定した商品の在庫数量を取得し、フォーマットされた数量を表示します。
サンプルコード 2: 在庫がない場合のメッセージ表示
$product = wc_get_product( $product_id );
if ( $product->is_in_stock() ) {
echo woocommerce_format_stock_quantity( $product->get_stock_quantity(), $product );
} else {
echo '在庫切れ';
}
このコードでは、商品が在庫切れの場合に「在庫切れ」と表示するサンプルです。
サンプルコード 3: カスタマイズされた在庫表示
function custom_stock_quantity_display( $quantity, $product ) {
return '残り ' . $quantity . ' 在庫あり';
}
add_filter( 'woocommerce_format_stock_quantity', 'custom_stock_quantity_display', 10, 2 );
このコードは在庫数量をカスタマイズして表示するためのフックの実装例です。
サンプルコード 4: ショートコードでの在庫表示
add_shortcode( 'stock_quantity', 'display_stock_quantity_shortcode' );
function display_stock_quantity_shortcode( $atts ) {
$atts = shortcode_atts( array('id' => 0), $atts );
$product = wc_get_product( $atts['id'] );
return woocommerce_format_stock_quantity( $product->get_stock_quantity(), $product );
}
このコードはショートコードを使用して在庫数量を表示します。IDを指定することで任意の商品在庫を表示可能です。
サンプルコード 5: 商品詳細ページでの在庫情報のカスタマイズ
add_action( 'woocommerce_single_product_summary', 'custom_stock_info', 25 );
function custom_stock_info() {
global $product;
if ( $product->is_in_stock() ) {
echo '<p>' . woocommerce_format_stock_quantity( $product->get_stock_quantity(), $product ) . '</p>';
}
}
このコードは商品詳細ページに在庫情報を表示するためのフックを使用した例です。