Добавить пользовательское уведомление в корзину в Woocommerce

Я хочу добавить пользовательское уведомление в корзину всякий раз, когда в корзину добавляется определенный товар (не все товары).

Сначала я хочу проверить количество, если оно равно 1, то я хочу отобразить уведомление, чтобы увеличить количество этого продукта. Я сам что-то понял из интернета и не думаю, что мое решение верное:

add_action( 'wp', 'sp_custom_notice' );

function sp_custom_notice() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

//to display notice only on cart page
if ( ! is_cart() ) {
return;
}

global $product;

$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
if($product_id == 15730){
//check for quantify if equal to 1 in cartwc_clear_notices();
wc_add_notice( __("Add one more to get 50% off on 2nd product"), 'notice');
}
}

Будет здорово, если кто-нибудь сможет мне помочь в этом.

2

Решение

Если вы все еще используете код из своего старого ответа, вы можете немного его изменить, чтобы это тоже заработало:

add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_2nd_at_50', 10, 1 );
function add_custom_discount_2nd_at_50( $wc_cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$discount = 0;
$items_prices = array();
$qty_notice = 0;  //  <==  Added HERE

// Set HERE your targeted variable product ID
$targeted_product_id = 40;

foreach ( $wc_cart->get_cart() as $key => $cart_item ) {
if( $cart_item['product_id'] == $targeted_product_id ){
$qty = intval( $cart_item['quantity'] );
$qty_notice += intval( $cart_item['quantity'] ); //  <==  Added HERE
for( $i = 0; $i < $qty; $i++ )
$items_prices[] = floatval( $cart_item['data']->get_price());
}
}
$count_items_prices = count($items_prices);
if( $count_items_prices > 1 ) foreach( $items_prices as $key => $price )
if( $key % 2 == 1 ) $discount -= number_format($price / 2, 2 );

if( $discount != 0 ){
// Displaying a custom notice (optional)
wc_clear_notices();
wc_add_notice( __("You get 50% of discount on the 2nd item"), 'notice');

// The discount
$wc_cart->add_fee( 'Discount 2nd at 50%', $discount, true  );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
//  <==  Here we display your additional notice when there quantity is equal to one
elseif( $qty_notice == 1){
wc_clear_notices();
wc_add_notice( __( "Add one more to get 50% off on 2nd product" ), 'notice');
}
}

Код помещается в файл function.php вашей активной дочерней темы (или темы) или также в любой файл плагина.

Этот код протестирован на Woocommerce 3+ и работает.

Замечания: wc_add_notice() функция абсолютно не нужно повторять

1

Другие решения

Вы сделали довольно хороший код, требуются небольшие изменения, попробуйте код ниже:

add_action('woocommerce_before_cart', 'sp_custom_notice');
function sp_custom_notice() {

if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

//to display notice only on cart page
if ( ! is_cart() ) {
return;
}

global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product =  wc_get_product( $values['data']->get_id());

if($values['data']->get_id() == 190 && $values['quantity'] == 1 ){
wc_clear_notices();
echo wc_add_notice( __("Add one more to get 50% off on 2nd product"), 'notice');
}
}
}
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector