Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce Custom Product Text

I'm trying to create a variable product using woocommerce which will include user input text which is specific to each product. To do so I am detecting for 'custom_text' type and displaying a text input field instead of the normal select-option dropdown.

This is in variable.php:

<form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo $post->ID; ?>">

    <?php 
    $loop = 0; foreach ( $attributes as $name => $options ) : $loop++; 

        <?php  if(is_array($options) && $options[0] == "custom_text") : //Name to be added to product ?> 
            <label for="<?php echo sanitize_title($name); ?>"><?php echo $woocommerce->attribute_label($name); ?></label></td>
            <input type="text" class="fullwidth req" id="<?php echo esc_attr( sanitize_title($name) ); ?>" name="attribute_<?php echo sanitize_title($name); ?>"/>
        <?php else : ?>
    ...

This is working except when you get to the cart page it is showing the input as all lower case with white spaces removed (changed to hyphens) etc.

Does anyone know where you could hook in and/or override this behavior? I have been trying everything to no avail.

Thanks

like image 602
Chizzle Avatar asked Dec 31 '13 20:12

Chizzle


1 Answers

I found the answer if anyone was wondering.

            // Get value from post data
            // Don't use woocommerce_clean as it destroys sanitized characters
            $value = sanitize_title( trim( stripslashes( $_REQUEST[ $taxonomy ] ) ) );

The previous is located on line 339 in woocommerce-functions.php. It needs to be changed to:

 $value = trim( stripslashes( $_REQUEST[ $taxonomy ] ) ) 

Now it's just a matter of overriding this file properly. I copied the original function from the woocommerce-functions.php and added it to my theme's functions.php. I then changed it so that it does not sanitize the user input.

This is what I added to my theme's functions.php:

add_action( 'init', 'override_add_to_cart_action' );
function override_add_to_cart_action( $url = false ) { // Original function is woocommerce_add_to_cart_action()
     // ... full function above and below
     $value = trim( stripslashes( $_REQUEST[ $taxonomy ] ) );
     // ...
}

By doing it this way we do not have to change any core files allowing us to update the plugin when needed. :)

like image 178
Chizzle Avatar answered Sep 25 '22 16:09

Chizzle