Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在购物车对象中添加自定义字段和变量的选定值_Php_Wordpress_Woocommerce_Product_Variations - Fatal编程技术网

Php 在购物车对象中添加自定义字段和变量的选定值

Php 在购物车对象中添加自定义字段和变量的选定值,php,wordpress,woocommerce,product,variations,Php,Wordpress,Woocommerce,Product,Variations,在WooCommerce中,我使用基于日期可用性的变量产品 在后端,我已成功添加了两个自定义字段,每个变量产品设置上都有自定义价格(成人/儿童)(两个自定义字段显示在底部): 这两个价格必须显示在相同的变量上,因为它们与相同的日期属性和数量相关联 问题 我可以在后端定义价格,在前端用数量选择器显示价格,但我不能在“单击”添加到购物车按钮的同时将价格添加到购物车。当用户单击“添加到购物车”按钮时,适当数量的成人将添加到购物车中,但我不知道如何添加儿童 事实上,我还想向购物车中添加另一个与相同变化

在WooCommerce中,我使用基于日期可用性的变量产品

在后端,我已成功添加了两个自定义字段,每个变量产品设置上都有自定义价格(成人/儿童)(两个自定义字段显示在底部):

这两个价格必须显示在相同的变量上,因为它们与相同的日期属性和数量相关联

问题
我可以在后端定义价格,在前端用数量选择器显示价格,但我不能在“单击”添加到购物车按钮的同时将价格添加到购物车。当用户单击“添加到购物车”按钮时,适当数量的成人将添加到购物车中,但我不知道如何添加儿童

事实上,我还想向购物车中添加另一个与相同变化相对应的项目,但具有子项价格和数量,以及类似“Price:children”的属性

我正在考虑使用add_to_cart功能,如:

add_to_cart( $product_id , $quantity , $variation_id, $variation , array(__('Price:','ah')=>__('Children','ah)) );
使用适当的
$product\u id
$variation\u id
$variation
,使用
$quantity
=子输入的数量,但我真的不知道在哪里和什么时候正确地包含这些

我尝试过的(但没有成功):

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();
    }

}   
  • 我尝试挂接到add_to_cart本身,但只成功创建了一个以错误结束的递归调用
  • 我也试着在计算总量之前加入woocommerce,但它似乎是改变价格的正确地方,但添加新产品并设定数量“为时已晚”
显示成人和儿童数量和价格
修改产品页面以显示2个价格,每个价格都有一个数量选择器,还有一个动态计算总价的jQuery脚本:

前端视图,带有价格和数量选择器,并自动计算总量

这是我的代码:

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();
    }

}   
功能、活动、产品、价格、显示(){
全球$产品;
$stock=$product->get_total_stock();
$pricepolicy=get_post_meta($product->id,'u ah_pricing',true);
if(is_activity()){
$price_list=array();
如果($pricepolicy=='multiple'){
$variations=$product->get_available_variations();
foreach($变更为$变更){
$variation_id=$variation['variation_id'];
$start=$variation['attributes']['attribute_date'];
$price_list[$start]['成人_price']=get_post_meta($variation_id,'u成人_price',true);
$price_list[$start]['children_price']=get_post_meta($variation_id,'u children_price',true);
}
//var_dump($price_list,json_encode($price_list));
?>


我几乎成功地实现了我想要的。以下是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程序员,只是一个自学的人…)

这将添加两种产品,属性为“定价”=>“成人”或“儿童”,以及相应的数量,但价格是变体的默认价格(不是我的自定义价格),因为我不知道如何将其包括在
WC()->cart->add_to_cart
call()。

好的,全部完成! 作为对我先前答案的补充,以下是我添加的代码,用于根据成人/儿童价格设置相应变化的价格,以防对其他人有所帮助:

/**
 * 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' );
结果如下:


谢谢。事实上,要对我想做的事情给出足够的解释并不是那么容易,同时也要尽量少。我担心遗漏细节,人们会认为这只是一个不知道如何使用Woocomece的人的基本问题……无论如何,我试着用必要的内容重写我的问题。非常感谢@LoicTheAztec用于格式化和澄清问题。在此期间,我几乎实现了我想要做的事情,使用Ajax回调(见下面的答案),感谢以下主题:我可以添加数量合适的两种产品,但我无法直接在ajax添加到购物车中设置价格。我在下面发布了代码和解决方案,但我的新问题是:打开一个新主题还是遵循这个主题更好?我已经对您的答案进行了评论。方法是创建一个新主题(新问题)对于一个新问题…最后一件事,你的代码中的注释应该是在该论坛上的英文…Aurélien,在Stackoverflow中,你不能将更新添加到你的问题作为答案。所以你可以做的是,将其添加为答案(和).然后你需要提出一个新问题,对于你需要解决的新问题…我知道你是新来的,所以我帮助你理解。