Reputation: 601
I have a Wordpress website build with Woocommcerce. I want to add some extra fields for users to be able to personalize their products ( some text inputs for them to write whatever they want). I thinks this needs to be done with custom attributes but I'm not sure.
I have tried this to add an extra attribute type:
add_filter("product_attributes_type_selector" , function( $array ){
$array["textfield"] = __( 'Textfield', 'woocommerce' );
return $array ;
});
I have no idea where to go on from this or if this is the right approach.
IMPORTANT NOTE: I don't want to use any plugins, so don't recommend any please
Upvotes: 1
Views: 3102
Reputation: 254483
Do it using a custom function hooked in woocommerce_before_add_to_cart_button
action hook, that will add a custom input text field before quantities field and add to cart button on variable products only:
// Adding a custom input text field before quantities field and add to cart button on variable products only
add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_fields' , 10, 0 );
function custom_product_fields() {
global $product;
if( ! $product->is_type( 'variable' ) ) return; // Only for variable products
echo '<div class="product-custom-fields">
<label class="my-custom-field1" for="custom_textfield1">'.__( 'Label text: ', 'woocommerce' ).'<br>
<input type="text" name="custom_textfield1" class="input-text" placeholder="'.__( 'Enter a text', 'woocommerce' ).'" value="">
</label>
</div>
<br clear="all">';
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works… so you will get something like:
You will use instead woocommerce_after_add_to_cart_button
action hook, if you want to display this custom field under add to cart button,
But you should need to save this custom field in cart object when added to cart and to display it in cart and checkout pages too.
Upvotes: 1