Reputation: 615
I've been trying to add an option on items on a cart so that the customer can rename the product. This is used for them to keep track of different products of the same type to be sent out to different people(making a hamper system)
I have used the woocommerce_cart_item_name
filter to add the input field to the cart items. I am using the answer from this link and trigger the wc_update_cart
in my javascript when the user will click the "ADD" button next to the input box, but it doesn't seem to be working at all.
Is there any other way that I can add this custom name data to the respective cart item after the product is added in? I know I can do it while add it to the cart( or a work around of removing that product and adding it back in with this new field. But don't want to do that)
Thanks in advance for your help.
Upvotes: 0
Views: 1303
Reputation: 615
Found the problem.
The "Add" button that I had next to the input box, which I was using to trigger the wc_update_cart
like jQuery(document).trigger('wc_update_cart');
was not validating the check I had put on the php side for the value of $_POST['update_cart']
. When I realised that I changed my woocommerce_cart_item_name
filter to only add the input box and use the Update Basket
button to update the name. So my code changed to:
<?php
add_filter('woocommerce_cart_item_name','custom_naming_front',10,3);
function custom_naming_front($product_title,$cart_item,$cart_item_key){
if(isset($cart_item['custom_name']) && !empty($cart_item['custom_name'])){
$product_title=$cart_item['custom_name'];
}
$product_title .= '<div class="custom-name-form-wrapper" id="custom-name'.$cart_item_key.'">
<input type="text" name="cart['.$cart_item_key.'][custom_name]" id="custom_name_text'.$cart_item_key.'" value="" placeholder="enter the name you want to give this product" />
</div>
</div>';
return $product_title;
}
?>
and the function to show update the name looks like:
<?php
function custom_name_save_to_cart(){
if ( ( ! empty( $_POST['apply_coupon'] ) || ! empty( $_POST['update_cart'] ) || ! empty( $_POST['proceed'] ) ) && isset( $_POST['_wpnonce'] ) && wp_verify_nonce( $_POST['_wpnonce'], 'woocommerce-cart' ) ) {
$cart_totals = isset( $_POST['cart'] ) ? $_POST['cart'] : '';
if ( ! WC()->cart->is_empty()) {
foreach ( WC()->cart->cart_contents as $cart_item_key => $values ) {
if ( ! isset( $cart_totals[ $cart_item_key ] ) || ! isset( $cart_totals[ $cart_item_key ]['custom_name'] ) ) {
continue;
}
WC()->cart->cart_contents[ $cart_item_key ]['custom_name'] = $cart_totals[ $cart_item_key ]['custom_name'];
}
}
}
}
add_action( 'wp_loaded', 'custom_name_save_to_cart', 25);
?>
Upvotes: 1