简体   繁体   中英

"Sales Badge" without sale price on Woocommerce

I'm working on woocommerce on wordpress, I want to make some sale badges but ignore the sales price (there are only regular prices).

I've tried it several times but the "sale badge" can only appear when I put the number on the sale price on the product

I use the code below

  add_filter('woocommerce_sale_flash', 'woocommerce_custom_sale_text', 10, 3);
function woocommerce_custom_sale_text($text, $post, $_product)
{
    global $post,$product;
    if ( ! $product->is_in_stock() ) return;
    $sale_price = get_post_meta( $product->id, '_price', true);
    $regular_price = get_post_meta( $product->id, '_regular_price', true);
    if (has_term('one', 'product_cat', $product->ID)) {
        return '<span class="onsale">one</span>';
    } elseif (has_term('two', 'product_cat', $product->ID)) {
        return '<span class="onsale">two</span>';
    } elseif (has_term('three', 'product_cat', $product->ID) || empty($sale_price)) {
        return '<span class="onsale">three</span>';
    }
    return '<span class="onsale">Sale</span>';
}

The filter itself is applied only if the product is on sale.

You need to overwrite the flash sale actions that happen before checking if the product is on sale.

first, remove the core flash sale hooks.

remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_show_product_loop_sale_flash', 10 );
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_sale_flash', 10 );

then, add your custom sale function instead.

add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_custom_sale_text', 10 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_custom_sale_text', 10 );

then use echo instead of return

function woocommerce_custom_sale_text()
{
    global $post,$product;
    if ( ! $product->is_in_stock() ) return;
    $sale_price = get_post_meta( $product->id, '_price', true);
    $regular_price = get_post_meta( $product->id, '_regular_price', true);
    if (has_term('one', 'product_cat', $product->ID)) {
        echo '<span class="onsale">one</span>';
    } elseif (has_term('two', 'product_cat', $product->ID)) {
        echo '<span class="onsale">two</span>';
    } elseif (has_term('three', 'product_cat', $product->ID) || empty($sale_price)) {
        echo '<span class="onsale">three</span>';
    }
    echo '<span class="onsale">Sale</span>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM