Set a specific product price conditionally on Woocommerce single product page & cart

前端 未结 2 723
挽巷
挽巷 2021-01-07 04:49

In Woocommerce I would like to alter the price of a specific product (in this case with an ID of 87) on both the single product page and for related cart items.

The

2条回答
  •  独厮守ぢ
    2021-01-07 05:15

    If you want to make it work to change the products price on single produt page. Please follow this code there I have added my product ID "99":

    add_action( 'woocommerce_single_product_summary', 'e_coding_change_simple_product_price_html', 9 );
    function e_coding_change_simple_product_price_html() {
        global $product;
    
    // Only for product ID 99
    if( $product->get_id() != 99 ) return;
    
    // HERE set your product category term ID, slug or name
    $product_category = 'my-book';
    
    // Checking for the product category in cart items loop
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( has_term( $product_category, 'product_cat', $cart_item['product_id'] ) )
            return; // Product category found ==> We EXIT from this function
    }
    
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
    add_action( 'woocommerce_single_product_summary', 'custom_simple_product_price_html', 10 );
    }
    
    function custom_simple_product_price_html(){
    global $product;
    
    $addp = 10; // Here the price additional amount
    
    if ( '' !== $product->get_price() && ! $product->is_on_sale() ) {
        $price = wc_price( wc_get_price_to_display( $product ) + $addp ) . $product->get_price_suffix();
    }
    echo '

    ' . apply_filters( 'woocommerce_get_price_html', $price, $product ) .'

    '; } // Add custom calculated price to cart item data add_filter( 'woocommerce_add_cart_item_data', 'add_cart_simple_product_custom_price', 20, 2 ); function add_cart_simple_product_custom_price( $cart_item_data, $product_id ){ // Only for product ID 87 if( $product_id != 99 ) return $cart_item_data; $product = wc_get_product($product_id); // The WC_Product Object // Only if product is not on sale if( $product->is_on_sale() ) return $cart_item_data; $price = (float) $product->get_price(); // Set the custom amount in cart object $cart_item_data['new_price'] = $price + 10; return $cart_item_data; } function cw_change_product_price_display( $price ) { $price .= ' At Each Item Product'; return $price; } add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' ); add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );

提交回复
热议问题