A
A
Andrey Plyuta2020-10-13 15:57:30
WordPress
Andrey Plyuta, 2020-10-13 15:57:30

Why is the selection in the wordpress form not working?

Actually, it was necessary to implement the function of gifts in the online store. The idea is that for each product, choose one of the products as a gift and display it in the product card, and so on.

But there was a problem, the product is selected, saved in the database, but for some reason, when updating the product card, it is not loaded.

Look, we select a product, the search works, the choice is made.
5f85a38bcbaad637926260.png

5f85a396a7e23547255052.png

But after saving, or subsequent opening of the product, it will not be displayed which gifts are selected.
5f85a3bd3c340940985132.png

<?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_ids = get_post_meta( $post->ID, '_gift_product_ids', true );
      $product_ids = ! empty( $gift_product_ids ) && isset($gift_product_ids) ? array_map( 'absint',  $gift_product_ids ) : 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_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 ;
    }


Please do not kick for the gamno code, but help, since I'm not a professional.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2020-10-13
@motor4ikkk

In general, a cool thing is a debugger. I highly recommend using.
A quick look shows that you are storing data in a meta field named _gift_product_idand reading from _gift_product_idsnote the last letter in the name.
The debugger would show you that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question