将输入字段添加到购物车中的每个项目

时间:2015-05-06 19:22:35

标签: woocommerce field cart

我正在尝试在cart.php文件中添加一个新字段。

我实际上想插入一个URL字段,因此用户可以为每个订单项设置一个URL。

我尝试使用其他帖子中的代码,但我无法让它工作。

第一个和第二个函数正在运行,但是当涉及到第三个函数时,'woocommerce_get_item_data' $cart_item['url']即使我在字段中添加了某些东西也不包含任何内容,我按下更新购物车。

来自第一个函数的

$cart_totals[ $cart_item_key ]['url']在页面加载时输出正确的值。

我现在不知道该怎么做,谢谢你的帮助。 这是代码

添加字段 车/ cart.php

<td class="product-url">
    <?php
        $html = sprintf( '<div class="url"><input type="text" name="cart[%s][url]" value="%s" size="4" title="Url" class="input-text url text" /></div>', $cart_item_key, esc_attr( $values['url'] ) );
        echo $html;
    ?>
</td>

的functions.php

// get from session your URL variable and add it to item
add_filter('woocommerce_get_cart_item_from_session', 'cart_item_from_session', 99, 3);
function cart_item_from_session( $data, $values, $key ) {
    $data['url'] = isset( $values['url'] ) ? $values['url'] : '';
    return $data;
}

// this one does the same as woocommerce_update_cart_action() in plugins\woocommerce\woocommerce-functions.php
// but with your URL variable
// this might not be the best way but it works
add_action( 'init', 'update_cart_action', 9);
function update_cart_action() {
    global $woocommerce;
    if ( ( ! empty( $_POST['update_cart'] ) || ! empty( $_POST['proceed'] ) ) ) {
        $cart_totals = isset( $_POST['cart'] ) ? $_POST['cart'] : '';
        if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
            foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
                if ( isset( $cart_totals[ $cart_item_key ]['url'] ) ) {
                    $woocommerce->cart->cart_contents[ $cart_item_key ]['url'] = $cart_totals[ $cart_item_key ]['url'];
                }
            }
        }
    }
}

// this is in Order summary. It show Url variable under product name. Same place where Variations are shown.
add_filter( 'woocommerce_get_item_data', 'item_data', 10, 2 );
function item_data( $data, $cart_item ) {
    if ( isset( $cart_item['url'] ) ) {
        $data['url'] = array('name' => 'Url', 'value' => $cart_item['url']);
    }
    return $data;
}

// this adds Url as meta in Order for item
add_action ('woocommerce_add_order_item_meta', 'add_item_meta', 10, 2);
function add_item_meta( $item_id, $values ) {
    woocommerce_add_order_item_meta( $item_id, 'Url', $values['url'] );
}

1 个答案:

答案 0 :(得分:0)

将 textarea 字段添加到 WooCommerce 购物车项目

首先,我们只需要添加 textarea 字段。我们使用 woocommerce_after_cart_item_name 钩子,这样我们的 textarea 就会出现在产品名称之后。

<?php
/**
 * Add a text field to each cart item
 */
function prefix_after_cart_item_name( $cart_item, $cart_item_key ) {
 $notes = isset( $cart_item['notes'] ) ? $cart_item['notes'] : '';
 printf(
 '<div><textarea class="%s" id="cart_notes_%s" data-cart-id="%s">%s</textarea></div>',
 'prefix-cart-notes',
 $cart_item_key,
 $cart_item_key,
 $notes
 );
}
add_action( 'woocommerce_after_cart_item_name', 'prefix_after_cart_item_name', 10, 2 );

/**
 * Enqueue our JS file
 */
function prefix_enqueue_scripts() {
 wp_register_script( 'prefix-script', trailingslashit( plugin_dir_url( __FILE__ ) ) . 'update-cart-item-ajax.js', array( 'jquery-blockui' ), time(), true );
 wp_localize_script(
 'prefix-script',
 'prefix_vars',
 array(
 'ajaxurl' => admin_url( 'admin-ajax.php' )
 )
 );
 wp_enqueue_script( 'prefix-script' );
}
add_action( 'wp_enqueue_scripts', 'prefix_enqueue_scripts' );
´´´
At the moment, the user will be able to enter text into the field but the text won’t save. We are going to use some AJAX to save the text.

The code above not only adds the textarea to the cart item, it also enqueues a JavaScript file ready for our AJAX.

It’s assumed that you’re using the code on this page to create a new plugin. If so, you should create a new JS file with the code below and place the file in the root directory of your plugin.

However, if you’ve added the PHP above to your theme functions.php or as a snippet on your site, you’ll need to change the location of the JS file by updating line 21 of the snippet above to identify the location of the JS file.

´´´
(function($){
 $(document).ready(function(){
 $('.prefix-cart-notes').on('change keyup paste',function(){
 $('.cart_totals').block({
 message: null,
 overlayCSS: {
 background: '#fff',
 opacity: 0.6
 }
 });
 var cart_id = $(this).data('cart-id');
 $.ajax(
 {
 type: 'POST',
 url: prefix_vars.ajaxurl,
 data: {
 action: 'prefix_update_cart_notes',
 security: $('#woocommerce-cart-nonce').val(),
 notes: $('#cart_notes_' + cart_id).val(),
 cart_id: cart_id
 },
 success: function( response ) {
 $('.cart_totals').unblock();
 }
 }
 )
 });
 });
})(jQuery);

´´´

Now, when the user types anything, the contents of the text field get sent back to the server ready to be saved as meta data to the cart item.

´´´
<?php
/**
 * Update cart item notes
 */
function prefix_update_cart_notes() {
 // Do a nonce check
 if( ! isset( $_POST['security'] ) || ! wp_verify_nonce( $_POST['security'], 'woocommerce-cart' ) ) {
 wp_send_json( array( 'nonce_fail' => 1 ) );
 exit;
 }
 // Save the notes to the cart meta
 $cart = WC()->cart->cart_contents;
 $cart_id = $_POST['cart_id'];
 $notes = $_POST['notes'];
 $cart_item = $cart[$cart_id];
 $cart_item['notes'] = $notes;
 WC()->cart->cart_contents[$cart_id] = $cart_item;
 WC()->cart->set_session();
 wp_send_json( array( 'success' => 1 ) );
 exit;
}
add_action( 'wp_ajax_prefix_update_cart_notes', 'prefix_update_cart_notes' );

function prefix_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
 foreach( $item as $cart_item_key=>$cart_item ) {
 if( isset( $cart_item['notes'] ) ) {
 $item->add_meta_data( 'notes', $cart_item['notes'], true );
 }
 }
}
add_action( 'woocommerce_checkout_create_order_line_item', 'prefix_checkout_create_order_line_item', 10, 4 );

´´´

The prefix_update_cart_notes function does a security check using the WooCommerce cart nonce then saves the content of the textarea as meta data in the cart item. You can check out this article for more information about updating cart meta for items that have already been added to the cart.

Add the custom text to the order meta
Finally, we want to pass our meta data to the order so that we can use it after the customer has checked out. The prefix_checkout_create_order_line_item function takes care of that, iterating through each item and saving notes when it finds them.


https://pluginrepublic.com/how-to-add-an-input-field-to-woocommerce-cart-items/
相关问题