How to change add-to-cart form? - woocommerce

Is there a way to change the WooCommerce add-to-cart form through functions.php?
The goal is to add a checkbox for an additional product. When the checkbox is checked this product will also be added to the cart after a click on the add to cart button.
I am looking for a solution which doesn't rely on javascript.

A better title would be "WooCommerce up-sells as checkboxes".
A lot of research and several strategies to tackle this problem lead me to a solution which I thought was not even possible in the beginning.
The solution is now exactly what I wanted. A non-JavaScript, no-template-override, but a simple and pure addition to functions.php. It works for simple and variable products (and probably with grouped and external products too).
It misses some nice features still. It won't work yet if an up-sell is a variable product. Quantity selection and limiting up-sells per item or order would be nice additions too. Based on the code below adding those features should not be a big deal anymore.
// create the checkbox form fields and add them before the cart button
add_action( 'woocommerce_before_add_to_cart_button', 'action_woocommerce_before_add_to_cart_form', 10, 0 );
function action_woocommerce_before_add_to_cart_form(){
global $woocommerce, $product;
// get the product up-sells
$upsells = $product->get_upsells();
// store the number of up-sells and pass it on to the add-to-cart hook
?>
<input type="hidden" name="upsells_size" value="<?php echo(sizeof($upsells)); ?>">
<div id="wb-upsell-div">
<?php
// iterate through all upsells and add an input field for each
$i = 1;
foreach( $upsells as $value ){
$product_id = $value;
?>
<input id="wb-upsell-checkboxes" type="checkbox" name="upsell_<?php echo($i) ?>" value="<?php echo($product_id); ?>"><?php echo( '' . get_the_title( $product_id ) . "". " ($" . get_post_meta( $product_id, '_regular_price', true) . ")"); ?><br>
<?php
$i++;
}
?>
</div>
<?php
}
// function to add all up-sells, where the checkbox have been checked, to the cart
add_action('woocommerce_add_to_cart', 'custom_add_to_cart', 10, 3);
function custom_add_to_cart() {
global $woocommerce;
// get the number of up-sells to iterate through
$upsell_size = $_POST['upsells_size'];
// iterate through up-sell fields
for ($i=1; $i<=$upsell_size; $i++){
// get the product id of the up-sell
$product_id = $_POST['upsell_' . $i];
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
And here is the CSS for formatting the <div>and the checkboxes. It goes into the style.css file:
#wb-upsell-div {
margin-top: 10px;
margin-bottom: 20px;
}
#wb-upsell-checkboxes{
}

So there's an actual answer to this question, you can add whatever you want inside the add to cart <form> using hooks. For example:
add_action( 'woocommerce_before_add_to_cart_button', 'so_34115452_add_input' );
function so_34115452_add_input(){
echo '<input type="checkbox" name="something"/>' . __( 'Some Checkbox', 'text-domain' );
}

Related

Woocommerce: add 'Free Delivery' badge to product thumbnail in Woocommerce based on shipping class

i want add, on product listing, over image a text badge "Free delivery" based on specific shipping class "spedizione-gratuita".
You can help me ?
I test this code but dont work
add_action( 'woocommerce_before_shop_loop_item_title', 'single_product_label', 10 );
function single_product_label() {
global $product;
$shipping_classes = 'spedizione-gratuita';
if ( $product->get_shipping_class() ) {
echo '<div class="spedizione-gratuita"><span class="freedel">SPEDIZIONE GRATUITA</span></div>';
}
}
Tnks
I believe this will achieve what you are trying to do. You almost had it, but the $product global has no value in the shop loop you need to use $post instead
add_action( 'woocommerce_before_shop_loop_item_title', 'single_product_label', 10 );
function single_product_label() {
global $post;
$_product = wc_get_product( $post->ID );
$shipping_classes = 'spedizione-gratuita';
if ( $shipping_classes == $_product->get_shipping_class() ) {
echo '<div class="spedizione-gratuita"><span class="freedel">SPEDIZIONE GRATUITA</span></div>';
}
}

Woocommerce product custom review tab hook

Hello I am creating a woocommerce wordpress website and I'm trying to replace the default reviews display with our own integration from Bazaarvoice. so I calledback the reviews tab to display my own function that gets the model number of the product and puts it into the code to display the bazaarvoice review display. The code works except that global $product doesn't work because I don't really know how to use hooks. I know the add_action for function bv_reviews_tab isn't correct so I'm not really sure what I am supposed to be putting there. I have been racking my head all day
add_filter( 'woocommerce_product_tabs', 'woo_renam_tabs', 98 );
function woo_renam_tabs( $tabs ) {
$tabs['additional_information']['title'] = __( 'Product Data' ); // Rename the additional information tab
$tabs['additional_information']['callback'] = 'woocommerce_product_additional_information_tab';
$tabs['reviews']['callback'] = 'bv_reviews_tab';
return $tabs;
}
add_action( 'woocommerce_product_tabs', ' bv_reviews_tab' );
function bv_reviews_tab( ) {
global $product;
if ( $product->is_type('simple' ) ) {
$model = esc_attr( get_post_meta( $product->get_id(), '_model_number', true ) );
}
elseif ( $product->is_type('variable' ) ) {
// Get childIDs in an array
$children_ids = $product->get_children();
// Loop
foreach ( $children_ids as $child_id ) {
// Get product
$product = wc_get_product( $child_id );
$model = esc_attr( get_post_meta( $child_id, '_model_number', true ) );
}
}
?>
<div
data-bv-show="reviews"
data-bv-product-id= "<?php echo $model; ?>"
>
</div>
<?php
}
There is no need of add_action in this case. The callback value given in the woo_renam_tabs function will trigger your custom function. Remove that add_action line and you should be good to go. global $product will also work.
Also, you will need to give a title to the reviews tab and ensure reviews tab is enabled in the WooCommerce >Settings > Products
This is the code that I have tested and is working:
add_filter( 'woocommerce_product_tabs', 'woo_renam_tabs', 98 );
function woo_renam_tabs( $tabs ) {
$tabs['additional_information']['title'] = __( 'Product Data' ); // Rename the additional information tab
$tabs['additional_information']['callback'] = 'woocommerce_product_additional_information_tab';
$tabs['reviews']['title'] = __( 'Reviews' ); ;
$tabs['reviews']['callback'] = 'bv_reviews_tab';
return $tabs;
}
function bv_reviews_tab() {
global $product;
?>
<div data-bv-show="reviews">
<?php echo $product->get_name();?>
</div>
<?php
}

WooCommerce Hook - woocommerce_after_cart_item_name

I am using a function to add custom meta to products. I have used the following hooks for SHOW on Product Loop woocommerce_after_shop_loop_item and Product Single Page woocommerce_product_meta_end.
So, when applying to get the same results on CART PAGE product/item by using the hook
woocommerce_after_cart_item_name it doesn’t work with no results.
Why isn’t the hook woocommerce_after_cart_item_name working if it works with the other previous hooks mentioned?
This the code I am using. I just change the hook to make it to show in Product Loop and Product Single Page, need it to show on cart Products as well. I was just wondering why it doesn't work with cart item hook..
public function woocommerce_after_cart_item_name()
{
global $product;
if ( !PluginOptions::value('shop_season') && !PluginOptions::value('shop_car_type') )
return;
$product_id = $product->get_id();
$season = get_post_meta( $product_id, 'season', true );
$car_type = get_post_meta( $product_id, 'car_type', true );
$tips_seasons = $this->ui_tips_season();
$tips_car_types = $this->ui_tips_car_types();
?>
<div class="tyre-details tyre-tips">
<?php if ( PluginOptions::value('shop_season') && $season ): ?>
<?php echo $tips_seasons[ strtolower($season) ]; ?>
<?php endif ?>
<?php if ( PluginOptions::value('shop_car_type') && $car_type ): ?>
<?php echo $tips_car_types[ strtolower($car_type) ]; ?>
<?php endif ?>
</div>
<?php
}
It is from a plugin. I was just given this code from woocommerce support but i do not know how to complete it. He says to replace with my meta_keys in the code which I will post below here. Can you help me finish this? or tell me where I need to replace. My meta_keys are $season and $car-type but i don't know how to apply with the code provided by woocommerce.
// Display custom cart item meta data (in cart and checkout)
add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_meta_data', 10, 2 );
function display_cart_item_custom_meta_data( $item_data, $cart_item ) {
$meta_key = 'PR CODE';
if ( isset($cart_item['add_size']) && isset($cart_item['add_size'] [$meta_key]) ) {
$item_data[] = array(
'key' => $meta_key,
'value' => $cart_item['add_size'][$meta_key],
);
}
return $item_data;
}
// Save cart item custom meta as order item meta data and display it everywhere on orders and email notifications.
add_action( 'woocommerce_checkout_create_order_line_item', 'save_cart_item_custom_meta_as_order_item_meta', 10, 4 );
function save_cart_item_custom_meta_as_order_item_meta( $item, $cart_item_key, $values, $order ) {
$meta_key = 'PR CODE';
if ( isset($values['add_size']) && isset($values['add_size'][$meta_key]) ) {
$item->update_meta_data( $meta_key, $values['add_size'][$meta_key] );
}
}
I located the ClassName (class FeatureTyreTips) and added that to the code you provided. I entered this in functions.php and it said fatal error when loading the cart page. I also tried placing it in the cart.php with same results...and I tried in the same plugin file where this code came from originally. All 3 locations did not work...only difference was that it did not show fatal error when adding and activating your new code in the plugin file when loading cart page. Any ideas? grazie Vdgeatano
The "Fatal Error" is most likely due to the fact that "the non-static method cannot be called statically": PHP - Static methods
I have now corrected the code.
Considering that the class name that was missing in your code is FeatureTyreTips, the correct code to add some text after the product name is:
add_action( 'woocommerce_after_cart_item_name', 'add_custom_text_after_cart_item_name', 10, 2 );
function add_custom_text_after_cart_item_name( $cart_item, $cart_item_key ) {
// create an instance of the "PluginOptions" class
$PluginOptions = new PluginOptions();
if ( ! $PluginOptions->value( 'shop_season' ) && ! $PluginOptions->value( 'shop_car_type' ) ) {
return;
}
$product = $cart_item['data'];
$season = get_post_meta( $product->get_id(), 'season', true );
$car_type = get_post_meta( $product->get_id(), 'car_type', true );
// create an instance of the "FeatureTyreTips" class
$FeatureTyreTips = new FeatureTyreTips();
$tips_seasons = $FeatureTyreTips->ui_tips_season();
$tips_car_types = $FeatureTyreTips->ui_tips_car_types();
if ( ! $PluginOptions->value('shop_season') || ! $season ) {
$season = '';
}
if ( ! $PluginOptions->value('shop_car_type') || ! $car_type ) {
$car_type = '';
}
$html = '<div class="tyre-details tyre-tips">' . trim( $season . ' ' . $car_type ) . '</div>';
echo $html;
}
The code has been tested (where possible) and works.It needs to be added to your theme's functions.php file or in your plugin.

Woocommerce product images replaced with a gallery plugin

First I would like to analyze my problem. Using Wordpress/Woocommerce I need to add videos beside images in the gallery of the product. Woocommerce does not support videos at all.
So, I thought to install an extra gallery plugin that supports both images and videos.
Now, I want to map a specific image/video gallery collection to a specific product. I want also to view this gallery collection in a new region that is not belong to the standard text fields like description or short description. Lets say above of the main product image. The php code that represent the gallery collection id=1 looks like below :
<?php echo do_shortcode('[wonderplugin_gallery id="1"]'); ?>
The problem is that I need the gallery collection id to be variable, something like this :
<?php echo do_shortcode('[wonderplugin_gallery id="X"]'); ?>
where X represnt the specific gallery collection. How the heck can I connect the gallery collection ID XXXX to my Product page XXXXX?
I have programming skills but I am new to the wordpress code logic.
Any other suggestions to my problem like plugins that may replace the default product gallery with better one ?
Regards,
I'd either use the product custom fields as Anand suggested, or create a metabox with the necessary input fields (or dropdowns depending on how you use the gallery plugin).
First I'd create a metabox, and in that metabox I'd pull the info from the plugin (gallery id's and names). Out of that you can create a dropdown. You should be able to select the id from that metabox for each product like you suggested. For instance something like this could work:
<?php
if ( ! function_exists( 'product_add_meta' ) ){
function product_add_meta(){
add_meta_box("gallery_dropdown", "Select Gallery", "product_gallery_meta_box", "product");
}
}
add_action("admin_init", "product_add_meta");
if ( ! function_exists( 'product_gallery_meta_box' ) ){
function product_gallery_meta_box( $post ){
$post_types = array('product'); //limit meta box to certain post types
global $post;
$product = get_product( $post->ID );
$values = get_post_custom( $post->ID );
$gallery = (isset($values['gallery'][0])) ? $values['gallery'][0] : '';
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<p>
<select name="gallery" id="gallery">
//example of how the option should look
<option value="<?php echo $gallery_id; ?>" <?php selected( $gallery, $gallery_id ); ?>><?php echo $gallery_name; ?></option>
<?php
//pull options from plugin here and create an option dropdown with foreach
?>
</select>
</p>
<?php
}
}
if ( ! function_exists( 'product_gallery_save_meta_box' ) ){
function product_gallery_save_meta_box( $post_id ){
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
return;
}
if( !isset( $_POST['gallery'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) {
return;
}
if( !current_user_can( 'edit_pages' ) ) {
return;
}
if( isset( $_POST['gallery'] ) ){
update_post_meta( $post_id, 'gallery', wp_kses( $_POST['gallery'] ,'') );
}
}
}
add_action( 'save_post', 'product_gallery_save_meta_box' );
If you put this in the functions.php, it should show a metabox called 'Select Gallery' with an empty dropdown on your woocommerce product page.
I haven't filled the options that you get from the plugin with which you create your galleries, but it shouldn't be too hard.
One way is to bind the product page id and gallery id. If you can change the id of a gallery then change it to match the id of the product page. Now you can create shortcode with any of these two examples.
// outside the loop use global ( uncomment appropriate statement )
// global $product;
// global $post;
do_shortcode( sprintf( '[wonderplugin_gallery id="%d"]', $product->id ) );
do_shortcode( sprintf( '[wonderplugin_gallery id="%d"]', $post->ID ) );
HERE is a link for plugin that reveals most of the IDs on admin pages.
Another is to create Custom Field ( post meta ) in edit product admin page ( named gallery_id for example ), and to save there id of the gallery to use. To create shortcode use get_post_meta() function that retrieves the saved post meta.
do_shortcode( sprintf( '[wonderplugin_gallery id="%d"]', get_post_meta( $post->ID, 'gallery_id', true ) ) );
To get the gallery id meta use $post->ID, $product->id, or get_the_ID() function, the latter only inside the loop.

WooCommerce: Add input field to every item in cart

I've been trying to add a single text input field to every item in the cart and submit that user input to product's meta info. It's been 2 days and I haven't succeeded yet.
My objective is to:
Take input from user for every item added to the cart.
Display that input in the order's meta info.
Display that input in confirmation email sent to the customer.
So far, I have copied the template file to my theme and added an input field inside a cell. I'm having trouble with the hooks, learned about hooks I will need from WooCommerce Product Gift Wrap plugin as indicated in this woocommerce issue.
Code I added to the cart.php template copied in my theme directory :
$input_url_data = '<div class="input-url"><input type="text" name="cart-url" value="" title="" class="input-text cart-url text" /></div>';
echo apply_filters( 'woocommerce_add_cart_item_data', $input_url_data, $cart_item_key );
Code I added to my theme's functions.php :
add_filter( 'woocommerce_add_cart_item_data','add_cart_item_data', 10, 2 );
add_filter( 'woocommerce_get_cart_item_from_session','get_cart_item_from_session', 10, 2 );
add_filter( 'woocommerce_get_item_data','get_item_data', 10, 2 );
add_filter( 'woocommerce_add_cart_item','add_cart_item', 10, 1 );
add_action( 'woocommerce_add_order_item_meta','add_order_item_meta', 10, 2 );
function add_cart_item_data( $cart_item_meta, $product_id ) {
$input_url_key = "";
$input_url_data['inputurl'] = $input_url_key;
return $input_url_data;
}
function get_cart_item_from_session( $cart_item, $values ) {
if ( ! empty( $values['inputurl'] ) ) {
$cart_item['inputurl'] = true;
}
return $cart_item;
}
function get_item_data( $item_data, $cart_item ) {
if ( ! empty( $cart_item['inputurl'] ) )
$item_data[] = array(
);
return $item_data;
}
function add_cart_item( $cart_item ) {
if ( ! empty( $cart_item['inputurl'] ) ) {
}
return $cart_item;
}
function add_order_item_meta( $item_id, $cart_item ) {
if ( ! empty( $cart_item['inputurl'] ) )
woocommerce_add_order_item_meta( $item_id, __( 'URL by buyer', 'custom_input_url' ), __( 'Yes', 'custom_input_url' ) );
}
Documentation about hook woocommerce_add_cart_item_data isn't very helpful and I'm stuck at this. How do I proceed?
There is a wordpress plugin called WC Fields Factory for the exact purpose.
You can also achieve this by using the following woocommerce hooks woocommerce_before_add_to_cart_button, woocommerce_add_to_cart, woocommerce_cart_item_name,and 'woocommerce_add_order_item_meta'
like for adding text field to product page
function add_name_on_tshirt_field() {
echo '<table class="variations" cellspacing="0">
<tbody>
<tr>
<td class="label"><label for="color">Name On T-Shirt</label></td>
<td class="value">
<input type="text" name="name-on-tshirt" value="" />
</td>
</tr>
</tbody>
</table>';
}
add_action( 'woocommerce_before_add_to_cart_button', 'add_name_on_tshirt_field' );
For displaying custom field on cart item table use the below
function render_meta_on_cart_item( $title = null, $cart_item = null, $cart_item_key = null ) {
if( $cart_item_key && is_cart() ) {
echo $title. '<dl class="">
<dt class="">Name On T-Shirt : </dt>
<dd class=""><p>'. WC()->session->get( $cart_item_key.'_name_on_tshirt') .'</p></dd>
</dl>';
}else {
echo $title;
}
}
add_filter( 'woocommerce_cart_item_name', 'render_meta_on_cart_item', 1, 3 );
to make your custom meta data on you order details, do some thing like this
function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
wc_add_order_item_meta( $item_id, "name_on_tshirt", WC()->session->get( $cart_item_key.'_name_on_tshirt') );
}
add_action( 'woocommerce_add_order_item_meta', 'tshirt_order_meta_handler', 1, 3 );
for detailed implementation, i have an article about how to do this without using any plugins. http://sarkware.com/how-to-pass-custom-data-to-cart-line-item-in-woocommerce-without-using-plugins/
It's easy. Try searching and reading code of Woocommerce.
This much of code got me to point where I can add Url # Cart. And I can see it in Order review as customer and as admin.
I can't test email because I'm lazy. I'm sorry.
Something like this goes in templates\cart\cart.php (there is need for some more code as it's seperate column)
<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'] ) ) && $woocommerce->verify_nonce('cart')) {
$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'] );
}
400$ is nice price.
You can do this fairly easily with the Woocommerce Product Add-ons plugin
From the WooThemes website:
Allow your customers to customise your products by adding new options
such as input boxes, dropdowns or checkboxes. With the Product Add-ons
extension, gift messages, donations, laser engraving and any other
product which may require user input in some way is now an option for
your customers!
Product add-ons supports required fields, textareas, checkboxes,
radios, select boxes, custom price inputs and file upload boxes.
I've used it before to add an additional donation field to a product purchase and display that on the thank you page/receipt email.
It's about $50 US and will get you up and running in no time to add the text input and display the field on thank you page/email like you want. $50 is definitely worth the amount of time you'd save drying to develop this feature yourself.
Here's the flow from the end-users perspective:
End user enters in field data and adds product to cart
When User views cart the data they entered into the custom field displays along with the product
After purchase, end user lands on thank you page and receives receipt email with field data included with the product item.
On the backend:
Create custom field for each product. The option is located on the Add-Ons menu tab.
Create a new Addon Group
Enter a group name (for easier organization)
Add a new option and enter the label (this is what the end user sees and is tied to the product)
Update/Publish product.
For completed orders, this is what you will see in the Order Details admin:
Hope this helps and saves you a ton of time in development!

Resources