【问题标题】:Add a select field that will change price in Woocommerce simple products添加将更改 Woocommerce 简单产品中价格的选择字段
【发布时间】:2018-09-26 11:21:59
【问题描述】:

我需要在单个产品中添加一个带有自定义价格的选择,如下面的屏幕截图所示;

这个想法是,通过从 (select) 中选择一个选项,您可以将其提高到基本价格。

不使用变体,因为我的想法是做更多其他事情,但我需要有关如何做到这一点的帮助。

我见过这样的插件称为“附加组件”,但我不想使用插件。

【问题讨论】:

    标签: php jquery wordpress woocommerce html-select


    【解决方案1】:

    要在简单产品(如可变产品)中添加一个选择字段,该字段将根据下拉选择值更新基本价格,请尝试以下操作:

    // Frontend: custom select field in product single pages
    add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' );
    function fabric_length_product_field() {
        global $product;
    
        if( $product->is_type('variable') ) return; // Not variable products
    
        $domain = 'woocommerce';
        $text   = array(
            __('cards', $domain),
            __('card', $domain),
            __('Total', $domain),
            get_woocommerce_currency_symbol(),
        );
    
        // Select Options array
        $options = array(
            ""          => __('Select package'),
            "12.00" => "1000 {$text[0]} - {$text[3]}0.012/{$text[1]} - {$text[2]} {$text[3]}12.00",
            "15.00" => "2000 {$text[0]} - {$text[3]}0.008/{$text[1]} - {$text[2]} {$text[3]}15.00",
            "20.00" => "3000 {$text[0]} - {$text[3]}0.007/{$text[1]} - {$text[2]} {$text[3]}20.00",
            "25.00" => "4000 {$text[0]} - {$text[3]}0.006/{$text[1]} - {$text[2]} {$text[3]}25.00",
        );
    
        // Select field
        woocommerce_form_field('cards_pack', array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Cards Pack selection', $domain),
            'required'      => true,
            'options'       => $options,
        ),'');
    
        // Data to be transmitted to jQuery
        $base_price = (float) wc_get_price_to_display( $product );
        $prices = array(
            ''      => wc_price($base_price),
            '12.00' => wc_price($base_price + 12),
            '15.00' => wc_price($base_price + 15),
            '20.00' => wc_price($base_price + 20),
            '25.00' => wc_price($base_price + 25),
        )
    
        // jQuery code
        ?>
        <script>
        jQuery(function($){
            var a = <?php echo json_encode($prices); ?>,
                b = 'p.price',
                c = 'select[name="cards_pack"]';
    
            $(c).on( 'change', function(){
                $.each( a, function( key, value ){
                    if( $(c).val() == key )
                        $(b).html(value);
                });
            });
        });
        </script>
        <?php
    }
    
    // Add selected pack data as custom data to cart items
    add_filter( 'woocommerce_add_cart_item_data', 'add_pack_data_to_cart_item_data', 20, 2 );
    function add_pack_data_to_cart_item_data( $cart_item_data, $product_id ){
        if( ! isset($_POST['cards_pack']) )
            return $cart_item_data;
    
        $pack_price = (float) sanitize_text_field( $_POST['cards_pack'] );
        if( empty($pack_price) )
            return $cart_item_data;
    
        if($pack_price == 12.00) $cards = 1000;
        elseif($pack_price == 15.00) $cards = 2000;
        elseif($pack_price == 20.00) $cards = 3000;
        elseif($pack_price == 25.00) $cards = 4000;
    
        $product    = wc_get_product($product_id); // The WC_Product Object
        $base_price = (float) $product->get_price();
    
        // New price calculation
        $new_price = $base_price + $pack_price;
    
        // Prepare and save the data array
        $cart_item_data['pack_data'] = array(
            'cards'     => (int)   $cards,
            'pack'      => (int)   $pack_price,
            'new_price' => (float) $new_price,
        );
        $cart_item_data['unique_key'] = md5( microtime() . rand() ); // Make each item unique
    
        return $cart_item_data;
    }
    
    // Set conditionally a custom item price
    add_action('woocommerce_before_calculate_totals', 'set_cutom_cart_item_price', 20, 1);
    function set_cutom_cart_item_price( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        foreach (  $cart->get_cart() as $cart_item ) {
            if ( isset( $cart_item['pack_data']['new_price'] ) )
                $cart_item['data']->set_price( $cart_item['pack_data']['new_price'] );
        }
    }
    
    
    // Display custom data in  checkout page
    add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
    function display_custom_cart_item_data( $cart_data, $cart_item ) {
        $domain        = 'woocommerce';
    
        if ( isset( $cart_item['pack_data']['new_price'] ) ){
            $cart_data[] = array('name' => __( 'Cards pack', $domain ),
                'value' => $cart_item['pack_data']['cards'] );
        }
        return $cart_data;
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试和工作。

    【讨论】:

    • @Loic 谢谢,但是这些数据没有显示在订单后端部分,我想看看支持的订单屏幕中选择了什么选项
    • @user3815413 这在这个问题中没有被问到……您应该搜索许多其他 StackOverFlow 线程,这些线程将向您展示如何在后端的订单屏幕中显示该数据……也可以在 "Customizing checkout fields using actions and filters" 中查看是一个代码 sn-p 这样做(接近尾声)......
    • @LoicTheAztec 你能看看这个吗:stackoverflow.com/questions/56125544/…
    • @LoicTheAztec,嗨,为什么购物卡上标题下方的价格是 2000 张卡的价格反映正确,但几秒钟后又恢复到原始价格?
    • @LoicTheAztec 其 woocommerce 迷你购物车,总金额正确,但迷你卡中每件商品的价格会在几秒钟内刷新并恢复原价
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2015-03-24
    • 2018-10-13
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多