库存数量简码
Stock quantity shortcode
我正在尝试创建一个短代码以放置在我的单个产品页面上,以便仅向管理员显示库存数量。对于普通客户,我只显示产品是否有货。这是我要创建的片段:
function Product_stock() {
if ( current_user_can( 'administrator' ) ) {
echo '<div class="sales-admin"><b>Available Stock (admin):</b><ol>';
global $product;
echo wc_get_stock_html( $product );
}
}
add_shortcode( 'Product_stock', 'Product_stock' );
但是上面的代码以我为我的 woocommerce 商店设置的格式显示库存,所以它再次以这种格式显示 Availability: In stock
或 Availability: Out of stock
.
我需要写什么来添加才能打印实际库存值?
一种解决方案是挂钩产品可用性文本。
你可以尝试类似的方法:
/**
* WC : add product quantity on front-end only to admins and shop managers
*/
add_filter( 'woocommerce_get_availability_text', 'a3w_woocommerce_get_availability_text', 10, 2);
function a3w_woocommerce_get_availability_text( $availability, $product ) {
if ( current_user_can( 'manage_woocommerce' ) ) { // replace 'manage_woocommerce' by 'administrator' for admin only OR any other condition
$availability .= sprintf( ' ( %d )', $product->get_stock_quantity() );
}
return $availability;
}, 20, 2 );
这将向管理员显示类似的内容:
Availability: In stock ( 18 )
致客户:
Availability: In stock
已测试并正常工作。
将此代码放在您的子主题的 functions.php 中。
我正在尝试创建一个短代码以放置在我的单个产品页面上,以便仅向管理员显示库存数量。对于普通客户,我只显示产品是否有货。这是我要创建的片段:
function Product_stock() {
if ( current_user_can( 'administrator' ) ) {
echo '<div class="sales-admin"><b>Available Stock (admin):</b><ol>';
global $product;
echo wc_get_stock_html( $product );
}
}
add_shortcode( 'Product_stock', 'Product_stock' );
但是上面的代码以我为我的 woocommerce 商店设置的格式显示库存,所以它再次以这种格式显示 Availability: In stock
或 Availability: Out of stock
.
我需要写什么来添加才能打印实际库存值?
一种解决方案是挂钩产品可用性文本。
你可以尝试类似的方法:
/**
* WC : add product quantity on front-end only to admins and shop managers
*/
add_filter( 'woocommerce_get_availability_text', 'a3w_woocommerce_get_availability_text', 10, 2);
function a3w_woocommerce_get_availability_text( $availability, $product ) {
if ( current_user_can( 'manage_woocommerce' ) ) { // replace 'manage_woocommerce' by 'administrator' for admin only OR any other condition
$availability .= sprintf( ' ( %d )', $product->get_stock_quantity() );
}
return $availability;
}, 20, 2 );
这将向管理员显示类似的内容:
Availability: In stock ( 18 )
致客户:
Availability: In stock
已测试并正常工作。
将此代码放在您的子主题的 functions.php 中。