2017-08-12 9 views
1

WooCommerceでは、バリエーションのある製品を使用しています。Woocommerceカートオブジェクトのバリエーションのカスタムフィールドを選択した値を追加

Screen shot of Back-end variations: The 2 custom fields at the bottom

は、バックエンドでは、私は、変数の各製品バリエーションでカスタム価格(大人/子供)の設定で正常に2カスタムフィールド(2つのカスタムフィールドが下部に表示されます)を追加しました

2つの価格は、同じ日付属性と数量にリンクされているため、同じバリエーションに表示する必要があります。

問題
私はカートに追加]ボタンを上「クリック」、バックエンドでの価格を定義するフロントエンド上の数量セレクターでそれらを示しているが、私は同じで、カートに追加することはできません。ユーザーがカートに追加ボタンをクリックすると、適切な数の大人がカートに追加されますが、子供を追加する方法もわかりません...

実際に私は同じバリエーションに対応するが、子供の価格と数量、および「価格:子供」のような属性に対応するカートの別のアイテム。

私は同じように、add_to_cart機能を使用して考えています

:= $quantityで、適切な$product_id$variation_id$variation

add_to_cart($product_id , $quantity , $variation_id, $variation , array(__('Price:','ah')=>__('Children','ah))); 

子供入力の数を、私は本当に知らない、いつどこでそれを適切に含めるためにフックする。私が試した(と動作しません)何

  • 私はadd_to_cart自体にフックしようとしたが、唯一のエラーで終了再帰呼び出しを作成することに成功しました。
  • 私はwoocommerce_before_calculate_totalsにもフックしようとしましたが、価格を変更するのに適しているようですが、新しい製品を追加して数量を設定するのは「遅すぎます」と思われます。

大人と子供の量の表示と価格
製品ページは、各数量セレクタで、2つの価格を表示するように変更され、また、動的に合計を算出し、jQueryのスクリプトです:

見ます価格及び数量の選択、ここで View of the front-end, with prices and quantity selector, and automatic calculation of total

の自動計算とフロントエンド、私のコードは:

function ah_activity_product_price_display() { 
    global $product; 
    $stock = $product->get_total_stock(); 
    $pricepolicy = get_post_meta($product->id, '_ah_pricing', true); 
    if(is_activity()) { 
     $price_list = array(); 
     if ($pricepolicy == 'multiple') { 
      $variations=$product->get_available_variations(); 
      foreach ($variations as $variation) { 
       $variation_id = $variation['variation_id'] ; 
       $start = $variation['attributes']['attribute_date']; 
       $price_list[$start]['adult_price'] = get_post_meta($variation_id, '_adult_price', true); 
       $price_list[$start]['children_price'] = get_post_meta($variation_id, '_children_price', true); 
      } 
      //var_dump($price_list,json_encode($price_list)); 
      ?> 
      <div class="multiple"> 
       <p class="clear"> 
        <div class="quantity"> 
         <input class="minus" type="button" value="-"> 
         <input type="number" step="1" min="1" max="<?php echo esc_attr(0 < $stock ? $stock : ''); ?>" name="nb_adulte" value="1" title="<?php echo esc_attr_x('Adult number', 'Product quantity input tooltip', 'ah'); ?>" class="input-text qty text" size="4" pattern="" inputmode="" /> 
         <input class="plus" type="button" value="+"> 
        </div> <?php _e('Adult x ','ah'); ?> <span class="prix-adulte"><?php esc_html($adult_price); ?></span> € 
       </p> 
       <p class="clear"> 
        <div class="quantity"> 
         <input class="minus" type="button" value="-"> 
         <input type="number" step="1" min="0" max="<?php echo esc_attr(0 < $stock ? $stock : ''); ?>" name="nb_enfant" value="0" title="<?php echo esc_attr_x('Children number', 'Product quantity input tooltip', 'ah'); ?>" class="input-text qty text" size="4" pattern="" inputmode="" /> 
         <input class="plus" type="button" value="+"> 
        </div> <?php _e('Children (under 18) x ','ah'); ?> <span class="prix-enfant"><?php echo esc_html($children_price); ?></span> € 
       </p> 
      </div> 
      <?php 
     } 
     echo '<input type="hidden" id="pricelist" name="pricelist" value=\''.json_encode($price_list).'\'>'; 

    } else { 
     woocommerce_get_price_html(); 
    } 

} 
+0

感謝。確かに、私がしたいことを十分に説明し、同時に最小限に抑えることは容易ではありません。私は細部が不足していることを恐れています。人々はそれが単調な言い回しを知らない人の基本的な質問だと思っています...とにかく、私は必要なものだけで質問を書き直そうとします。 –

+0

@LoicTheAztecを書式化して質問をクリアしてくれてありがとう。それまでの間、私はAjaxコールバック(下記の回答を参照)を使用して、私がやりたいことをほぼ達成しました。次のトピックを参考にしてください:https://stackoverflow.com/questions/27270880/add-a-variation-to-カートに入れる - ajax-woocommerce-api?noredirect = 1&lq = 1 2個の商品を適切な数量で追加できますが、ajaxでカートに追加することで価格を直接設定することはできません。私はここにコードとソリューションを掲載しましたが、私の新しい質問のために、新しいトピックを開く方が良いでしょうか、これに従うのが良いでしょうか? –

+0

私はあなたの答えをコメントしました。方法は新しい質問のための新しいトピック(新しい質問)を作ることです...最後のものは、あなたのコードのコメントは、そのフォーラムに英語でなければなりません... – LoicTheAztec

答えて

2

私が欲しいものを達成するのにほぼ成功しました。ここではPHPで追加したコードです:

/** 
* Définition et paramètres des scripts pour ajout au panier 
*/ 
add_action('wp_enqueue_scripts', 'ah_load_script', 20); 
function ah_load_script(){ 
    wp_enqueue_script('ah_ajax_add_to_cart', get_stylesheet_directory_uri() . '/js/test.js'); 
    $i18n = array('ajax_url' => admin_url('admin-ajax.php'), 'checkout_url' => get_permalink(wc_get_page_id('checkout'))); 
    wp_localize_script('ah_ajax_add_to_cart', 'ah_add_to_cart_params', $i18n); 
} 
/** 
* Fonction d'ajout au panier Ajax 
*/ 
add_action('wp_ajax_myajax', 'ah_add_to_cart_callback'); 
add_action('wp_ajax_nopriv_myajax', 'ah_add_to_cart_callback'); 

    /** 
    * AJAX add to cart. 
    */ 
function ah_add_to_cart_callback() {   
    ob_start(); 
    //$product_id  = 264; 
    $product_id  = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id'])); 
    $quantity   = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']); 
    $variation_id  = isset($_POST['variation_id']) ? absint($_POST['variation_id']) : ''; 
    $variations   = ! empty($_POST['variation']) ? (array) $_POST['variation'] : ''; 

    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data); 
    $product_status = get_post_status($product_id); 
    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variations) && 'publish' === $product_status) { 
     do_action('woocommerce_ajax_added_to_cart', $product_id); 
     wc_add_to_cart_message($product_id); 
    } else { 
     // If there was an error adding to the cart, redirect to the product page to show any errors 
     $data = array(
      'error'  => true, 
      'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id) 
     ); 
     wp_send_json($data); 
    } 
    die(); 
} 

は、これはコードが醜いであれば、対応するJSが(恐れ入りますが、私は本当のJSコーダー、単に自己学習ではありませんよ...):

jQuery(document).ready(function($){ 

    $(".test-button").click(function(e){ 
    e.preventDefault(); // Prevent the click from going to the link 
    $variation_form = $(this).closest('.variations_form'); 
    var product_id = $variation_form.find('input[name=product_id]').val(); 
    var adult_qty = $variation_form.find('input[name=nb_adulte]').val(); 
    var children_qty = $variation_form.find('input[name=nb_enfant]').val(); 
    var adult_price = $variation_form.find('.prix-adulte').text(); 
    var children_price = $variation_form.find('.prix-enfant').text(); 

    var var_id = $variation_form.find('input[name=variation_id]').val(); 
    var att_date = $variation_form.find('select[name=attribute_date]').val(); 
    var att_adult = "adulte"; 
    var att_children = "enfant"; 

    $.ajax({ 
     url: ah_add_to_cart_params.ajax_url, 
     method: 'post', 
     data: { 
      'action': 'myajax', 
      'product_id': product_id, 
      'quantity': adult_qty, 
      'price' : adult_price, 
      'variation_id': var_id, 
      'variation': { 'attribute_date': att_date, 'attribute_tarif': att_adult } 
     } 
    }).done(function (response) { 
     if(response.error != 'undefined' && response.error){ 
     //some kind of error processing or just redirect to link 
     // might be a good idea to link to the single product page in case JS is disabled 
     return true; 
     } else { 
     $.ajax({ 
      url: ah_add_to_cart_params.ajax_url, 
      method: 'post', 
      data: { 
       'action': 'myajax', 
       'product_id': product_id, 
       'quantity': children_qty, 
       'price' : children_price, 
       'variation_id': var_id, 
       'variation': { 'attribute_date': att_date, 'attribute_tarif': att_children } 
      } 
     }).done(function (response) { 
      if(response.error != 'undefined' && response.error){ 
      //some kind of error processing or just redirect to link 
      // might be a good idea to link to the single product page in case JS is disabled 
      return true; 
      } else { 
      window.location.href = ah_add_to_cart_params.checkout_url; 
      } 
     }); 
     } 
    }); 
    }); 
}); 

これは、属性「価格」=>「大人」や「子供」、および対応する量で、2つの製品が追加されますが、価格が変動(ない私のカスタム価格)のデフォルトの価格です私はそれをWC()->cart->add_to_cartコール(see how my cart looks with the above code for 5 adult, 2 children)に含める方法がわからないからです。

+0

Aurélien、Stackoverflowであなたの質問に更新を追加することはできません回答。あなたができることは、それを答えとして追加することです(そして、正しい答えとして受け入れることです**)(https://stackoverflow.com/help/someone-answers))。それから、あなたは解決しなければならない新しい問題のために、新しい質問をする必要があります...私はあなたが新しいことを知っています。 – LoicTheAztec

0

さて、すべて完了!ここで私の前の回答の補数で は、私が大人/子供と一緒に対応する変化の価格を設定するために追加されたコードのビットがそれに応じて価格である場合、それは他の誰かを助けることができる:

/** 
* Override price in cart in case of adult/children prices 
*/ 
function ah_add_custom_price($cart_object) { 
    $custom_price = 10; // This will be your custom price 
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { 
     //var_dump($cart_item); 
     $my_item = $cart_item['variation']; 
     $adult_price = get_post_meta($cart_item['variation_id'], "_adult_price" , true); 
     $children_price = get_post_meta($cart_item['variation_id'], "_children_price" , true); 
     if (array_key_exists('attribute_tarif', $my_item)) { 
      if (($my_item['attribute_tarif'] == "adulte") && (isset($adult_price))) { 
       $cart_item['data']->set_price($adult_price); 
      } elseif (($my_item['attribute_tarif'] == "enfant") && (isset($children_price))) { 
       $cart_item['data']->set_price($children_price); 
      } 
     } 

    } 
} 
add_action('woocommerce_before_calculate_totals', 'ah_add_custom_price'); 

をそしてここにあります結果: Product page with adult/children prices

Cart with custom attribute and custom price

関連する問題