A
A
Andrey Plyuta2020-10-14 17:58:00
WordPress
Andrey Plyuta, 2020-10-14 17:58:00

How to add a gift to the basket and order?

I make functional gifts for the site. The essence of the work is this. The seller in the card of each item selects a gift item.
It looks like this:
5f870fa15caf8330192222.png

In the product card it is displayed like this:
5f8711330de9d560674260.png

Now I can’t figure out how to add it to the cart, and the order itself. For example, when a customer adds this product to the cart, the gift was already there. And when ordering too.

Help than you can, please do not kick much, I'm just learning).
Here is the code:

<?php
/*
 * Plugin Name: Gift for Products
 * Plugin URI: https://triniti.biz.ua
 * Description: Подарки для товаров 
 * Version: 0.1
 * Author: Andrey
 * Author URI: https://triniti.biz.ua
 * License: GPLv2 or later
 */
add_action( 'woocommerce_product_options_general_product_data', 'woo_marketing_fields' );
function woo_marketing_fields() {
  global $product, $post;
  echo '<div class="options_group">';
  
woocommerce_wp_select( array(
   'id'      => '_select_bonus',
   'label'   => 'Параметри промо-акції',
   'options' => array(
      'active'   => __( 'Акція не проводиться', 'woocommerce' ),
      '100uah'   => __( 'Бонус 100 грн', 'woocommerce' ),
      '200uah' => __( 'Бонус 200 грн', 'woocommerce' ),
   ),
) );
?>
<p class="form-field gift_product_type">
   <label for="gift_product_type">Вибір подарунка</label> <select id="gift_product_type"
      name="gift_product_type[]" class="wc-product-search" multiple="multiple" style="width: 50%;" data-placeholder="<?php esc_attr_e( 'Пошук подарункових товарів…', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" data-exclude="<?php echo intval( $post->ID ); ?>">
      <?php
      $gift_product_id = get_post_meta( $post->ID, '_gift_product_id', true );
      $product_ids = ! empty( $gift_product_id ) && isset($gift_product_id) ? array_map( 'absint',  $gift_product_id ) : array();
      if ( $product_ids ) {
         foreach ( $product_ids as $product_id ) {
            $product      = wc_get_product( $product_id );
            $product_name = $product->get_formatted_name();
            echo '<option value="' . esc_attr( $product_id ) . '" ' . selected(true, true, false )  . '>' .
                 esc_html( $product->get_formatted_name() ) . '</option>';
         }
      }
      ?>
      </select><span class="woocommerce-help-tip" data-tip="Обраний подурунок буде відображатись в карточці товару"></span>
   </p>
   <?php
   echo '</div>';
}

 //Вывод подарков в карточке товара///

add_action( 'woocommerce_single_product_summary', 'get_gift_product', 40 ); //Место размещения
//Получаем данные
function get_gift_product() {
  global $post;
   $product_field_id = get_post_meta( $post->ID, '_gift_product_id', true );
   $product_ids_gift = ! empty( $product_field_id ) && isset($product_field_id) ? array_map( 'absint',  $product_field_id ) : array();
   if ($product_ids_gift){
   $product_lists = wc_get_products( array(
    'include'        => $product_ids_gift,
   ));
   //Выводим в карточке товара
   echo '<div class="rol-thumb-cnt">
   <div class="rol-thumb-title">ПОДАРУНОК</div>';
  foreach ($product_lists as $list){
   echo '<div class="rol-thumb">' . $list->get_image([0]) .'
   <a href="'. get_permalink($list->get_ID()) .'" class="product-gift-title">'. $list->get_name() .'</a>';
   echo '<div class="price_gift"><del><span class="woocommerce-Price-amount amount"> '. $list->get_price() .' грн</span></del><span class="woocommerce-Price-amount amount" id="gift">БЕЗКОШТОВНО</div></div>';
      // echo '<div class="gift_img">'. $list->get_image() .'';
      //echo'<a href="'. get_permalink($list->get_ID()) .'">'. $list->get_formatted_name() .'</a></div>';
  }
   echo '</div>';}
}
//Конец кода с выводом подарков

add_action( 'woocommerce_process_product_meta', 'woo_marketing_fields_save', 10 );
function woo_marketing_fields_save( $post_id ) {
   // Cохраняем выбраный бонус
   $woocommerce_select = $_POST['_select_bonus'];
   if ( ! empty($woocommerce_select )) {
      update_post_meta( $post_id, '_select_bonus', esc_attr( $woocommerce_select ) );
   }
// Сохранение произвольного поля по выбору товаров с поиском
    if (  isset( $_POST['gift_product_type'] ) && !empty($_POST['gift_product_type'] ) ) {
      // Проверяем данные, если они существуют и не пустые, то записываем данные в поле
      update_post_meta( $post_id, '_gift_product_id',  array_map( 'absint', (array) $_POST['gift_product_type'] ));
   } else {
      // Иначе удаляем созданное поле из бд
      delete_post_meta( $post_id, '_gift_product_id');
   }
}

//Вивод кнопки "Получить бонус"
function product_bonus_button() {
  global $post, $product;
  $bonus_select = get_post_meta( $post->ID, '_select_bonus', true );
  if ( $bonus_select == "200uah") {
      echo do_shortcode('[html_block id="17170"]'); }
  elseif ( $bonus_select == "100uah") {
      echo do_shortcode('[html_block id="17174"]'); }
  else ;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2020-10-14
@pton

So you can't do this in one function
- At the time of adding a product, you need to add one more product.
- To account for the value of the gift, you can add a discount to the order.
- Think about the option to remove the gift if the user removes the main product.
As an example below. Taken from a real project. Because the action was one-time, I did not bother with the settings and hardcoded the identifiers in the code.
The gift product "Ball" is added if the user puts any product from the "promotion" taxonomy with id=1280 into the cart

/**
 * Add product id=42444 "ball STORM PRO HB" to cart if added any product from
 * promotion 1280
 *
 * @param $cart_item_key Current cart item key.
 * @param $product_id    Current product id (parent id for variations).
 *
 * @throws Exception
 */
function hml_woocommerce_add_to_cart( $cart_item_key, $product_id ) {
  $tax     = 'promotion';
  $term_id = 1280;
  if ( ! has_term( $term_id, $tax, $product_id ) ) {
    return;
  }

  foreach ( WC()->cart->get_cart() as $cart_item ) {
    $product_in_cart = $cart_item['product_id'];
    if ( $product_in_cart === 42444 ) {
      return;
    }
  }

  WC()->cart->add_to_cart( 42444, 1, 42450 ); // аргументы: id-товара, кол-во, id-разновидности(вариации)
}

add_action( 'woocommerce_add_to_cart', 'hml_woocommerce_add_to_cart', 10, 2 );

The code below replaces the quantity selection field for the gift item, but makes the input hidden so that woo can process it.
/**
 * Filter quantity input tag for cart item.
 * Actualy replace input tag with const "1" for certain products
 *
 * @param $product_quantity Default output.
 * @param $cart_item_key    Current cart item key.
 * @param $cart_item        Current cart item.
 *
 * @return string
 */
function hml_woo_cart_item_quantity( $product_quantity, $cart_item_key, $cart_item ) {
  $product_in_cart = $cart_item['product_id'];
  if ( $product_in_cart === 42444 ) {
    $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
  }
  return $product_quantity;
}

add_filter( 'woocommerce_cart_item_quantity', 'hml_woo_cart_item_quantity', 10, 3 );

to add a discount (compensation for the price of a gift item) to an order, you can use the 'woocommerce_cart_calculate_fees'
With Deletion hook, I didn’t bother, so I won’t be able to suggest a hook. you have to google.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question