首页 > 解决方案 > 在 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 );

有什么建议吗?

标签: phpwordpresswoocommerceproductcustom-fields

解决方案


您的代码包含一些错误

  • 过滤器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 = '';
}

推荐阅读