Nat*_*nch 0 php wordpress shortcode woocommerce product-quantity
我正在尝试在普通的WordPress页面或帖子中的WoCommerce页面之外显示给定产品ID的产品数量。
我假设您将一些代码粘贴到functions.php中,然后在您的帖子或页面中添加了一个代码段。
我在这里真的很挣扎,到目前为止,我发现的答案只是半生半熟,而这些答案都不适合我。
如何在正常的Wordpress页面或帖子上回显WooCommerce产品ID的库存数量?
最好的方法是创建一个自定义的简码功能,该功能将输出给定产品ID的产品数量。
此简码功能的代码:
if( !function_exists('show_specific_product_quantity') ) {
function show_specific_product_quantity( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts(
array(
'id' => '', // Product ID argument
),
$atts,
'product_qty'
);
if( empty($atts['id'])) return;
$stock_quantity = 0;
$product_obj = wc_get_product( intval( $atts['id'] ) );
$stock_quantity = $product_obj->get_stock_quantity();
if( $stock_quantity > 0 ) return $stock_quantity;
}
add_shortcode( 'product_qty', 'show_specific_product_quantity' );
}
Run Code Online (Sandbox Code Playgroud)
代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中。
用法
简码与
ID参数(目标产品ID)一起使用。
1)在WordPress页面或帖子内容中,只需将此简短代码粘贴到文本编辑器中即可显示给定产品ID的库存数量(此处ID为37):
[product_qty id="37"]
Run Code Online (Sandbox Code Playgroud)
2在任何PHP代码中(示例):
echo '<p>Product quantity is: ' . do_shortcode( '[product_qty id="37"]' ) .'</p><br>';
Run Code Online (Sandbox Code Playgroud)
3在HTML / PHP页面(示例)中:
if( !function_exists('show_specific_product_quantity') ) {
function show_specific_product_quantity( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts(
array(
'id' => '', // Product ID argument
),
$atts,
'product_qty'
);
if( empty($atts['id'])) return;
$stock_quantity = 0;
$product_obj = wc_get_product( intval( $atts['id'] ) );
$stock_quantity = $product_obj->get_stock_quantity();
if( $stock_quantity > 0 ) return $stock_quantity;
}
add_shortcode( 'product_qty', 'show_specific_product_quantity' );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5452 次 |
| 最近记录: |