通过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', 10, 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', 10, 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;
}

Replace

// 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', 'filter_woocommerce_post_class', 10, 2 );

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

最新更新