通过 WooCommerce 产品设置中的自定义复选框向 WooCommerce 页面添加类

问题描述

我对下面的代码有疑问。使用该代码,我们可以选择特定产品并在商店档案中为它们提供不同的样式。这是有效的。

但是,我猜代码中有错误

一旦我激活了产品的复选框,即使我取消选中该复选框,它也始终以新样式显示。我假设我在使用 get_post_meta 对象时出错。

有人可以帮我吗?

用于在常规产品设置中显示复选框并添加类的代码,基于复选框中的值

// Add checkBox
function action_woocommerce_product_general_options_product_style_listing_data() {
    // CheckBox
    woocommerce_wp_checkBox( array( 
        'id'             => '_special_product_listing_style',// required,it's the Meta_key for storing the value (is checked or not)
        'label'          => __( 'Special style','woocommerce' ),// Text in the editor label
        'desc_tip'       => false,// true or false,show description directly or as tooltip
        'description'    => __( 'Promote a product by changing the style of the product card','woocommerce' ) // Provide something useful here
    ) );
}
add_action( 'woocommerce_product_options_general_product_data','action_woocommerce_product_general_options_product_style_listing_data',10,0 );
        
// Save Field
function action_woocommerce_product_general_options_product_style_listing_save( $product ) {
    // Isset,yes or no
    $checkBox = isset( $_POST['_special_product_listing_style'] ) ? 'yes' : 'no';

    // Update Meta
    $product->update_Meta_data( '_special_product_listing_style',$checkBox );
}
add_action( 'woocommerce_admin_process_product_object','action_woocommerce_product_general_options_product_style_listing_save',1 );

// Is_special style
function filter_woocommerce_post_class( $classes,$product ) {    
    if ( get_post_meta( $product->get_id(),'_special_product_listing_style',true ) ) {
        $classes[] = 'custom-product-listing-class';
    }
    return $classes;
}
add_filter( 'woocommerce_post_class','filter_woocommerce_post_class',2 );

用于设置特定产品样式的 CSS:

/* Custom special product listing style */
li.sales-flash-overlay.woocommerce-text-align-left.woocommerce-image-align-center.do-quantity-buttons.product.type-product.post-10800.status-publish.first.instock.product_cat-crafty-beer-club.has-post-thumbnail.featured.sold-individually.taxable.shipping-taxable.product-type-variable.custom-product-listing-class {
    border: 2px solid;
    border-style: dashed;
}

解决方法

替换

// Is_special style
function filter_woocommerce_post_class( $classes,$product ) {    
    if ( get_post_meta( $product->get_id(),'_special_product_listing_style',true ) ) {
        $classes[] = 'custom-product-listing-class';
    }
    return $classes;
}
add_filter( 'woocommerce_post_class','filter_woocommerce_post_class',10,2 );

// Is_special style
function filter_woocommerce_post_class( $classes,$product ) {
    // Get meta
    $spls = $product->get_meta( '_special_product_listing_style' );
    
    // Compare
    if ( $spls == 'yes' ) {
        $classes[] = 'custom-product-listing-class';
    }
    
    return $classes;
}
add_filter( 'woocommerce_post_class',2 );

这应该足以让您的代码完全运行