php - 在 WooCommerce 的单个产品页面上隐藏某些产品的产品库存
问题描述
我尝试添加一个选项来隐藏产品库存信息,但仅在某些单个产品页面上。
我们不想为每个产品隐藏此信息。我们希望在产品编辑视图中有一个选项,我们可以在其中选择当前产品是否应该是这种情况。
不幸的是,我下面的代码没有完全工作。没有致命错误,但选中复选框时代码不会隐藏产品的库存信息。
这是我到目前为止所拥有的:
// Add checkbox
function action_woocommerce_hide_product_stock_info() {
// Checkbox
woocommerce_wp_checkbox( array(
'id' => '_hide_stock_status', // Required, it's the meta_key for storing the value (is checked or not)
'label' => __( 'Hide product stock info', 'woocommerce' ), // Text in the editor label
'desc_tip' => false, // true or false, show description directly or as tooltip
'description' => __( 'Dont show product stock info on product page', 'woocommerce' ) // Provide something useful here
) );
}
add_action( 'woocommerce_product_options_inventory_product_data', 'action_woocommerce_hide_product_stock_info', 10, 0 );
// Save Field
function action_woocommerce_hide_product_stock_info_object( $product ) {
// Isset, yes or no
$checkbox = isset( $_POST['_hide_stock_status'] ) ? 'yes' : 'no';
// Update meta
$product->update_meta_data( '_hide_stock_status', $checkbox );
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_hide_product_stock_info_object', 10, 1 );
// Hide stock info on product page
function filter_woocommerce_hide_product_stock( $html, $text, $product ) {
// Get meta
$hide_product_stock_info = $product->get_meta( '_hide_stock_status' );
// Compare
if ( $hide_product_stock_info == 'yes' ) {
// Hide product stock info
if ( isset( $availability['class'] ) && 'in-stock' === $availability['class'] ) {
return '';
}
return $html;
}
}
add_filter( 'woocommerce_stock_html', 'filter_woocommerce_hide_product_stock', 10, 2 );
有什么建议吗?
解决方案
您的代码包含一些错误
- 过滤器
woocommerce_stock_html
已弃用。woocommerce_get_stock_html
改为使用 $availability
没有定义- 函数的参数太少
filter_woocommerce_hide_product_stock()
,传入了 2 个......并且预期正好有 3 个
因此,将代码的第三部分替换为:
// Hide stock info on product page
function filter_woocommerce_get_stock_html( $html, $product ) {
// Get meta
$hide_product_stock_info = $product->get_meta( '_hide_stock_status' );
// Compare
if ( $hide_product_stock_info == 'yes' ) {
$html = '';
}
return $html;
}
add_filter( 'woocommerce_get_stock_html', 'filter_woocommerce_get_stock_html', 10, 2 );
可选:您的问题中未提及,但如果您仍想扩展基于 的功能$availability
,您可以添加以下内容:
// Get availability
$availability = $product->get_availability();
// Condition
if ( ! empty( $availability['availability'] ) && $availability['class'] == 'in-stock' ) {
$html = '';
}
推荐阅读
- java - 字段未出现在 Firebase Android Studio 的数据库中
- javascript - 如何从构造函数 JavaScript 复制“this”
- html - 如果用户触摸后输入为空/不正确,则显示不同的错误消息
- c - 基本 C 程序中的循环
- post - 使用 Volley 和 Kotlin 创建发布请求
- python - 如何在 Python 3 中将 ["+5*-5"] 等字符串列表元素转换为 [+5*-5]
- mysql - dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib when running nginx and mysql after macOS upgrade to Catalina
- python - 未知初始化器:Cube.AI 中带有 Keras 的 GlorotUniform
- angular - 使用 ID 订阅 Angular 组件
- c - 如何动态地将字符串插入到 C 结构内的二维数组中?