Woocommerce Custom Product Text

怎甘沉沦 提交于 2019-12-05 00:18:06

问题


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


回答1:


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. :)



来源:https://stackoverflow.com/questions/20862740/woocommerce-custom-product-text

工具导航Map