Learning WooCommerce Development by Example Sample
Learning WooCommerce Development by Example Sample
By Example
How to Use This Book 14
Pros and Cons of Adding Snippets to the functions.php File in Your Theme
19
Pros and Cons of Adding Snippets to the functions.php File in Your Child
Theme 20
Final Thoughts 29
Why bother with do_action and add_action couldn’t we just write stuff directly to the page?
35
A Contrived Example 37
Priority 39
Removing Filters 40
Passing Arguments 40
Final Thoughts 46
FTP 51
Is There a Way to Add Permanent CSS and Code Changes Without Creating
a Child Theme 60
What are Variable Products and when should you use them? 72
Local by Flywheel 81
Conclusion 94
Final Thoughts 99
Problem 102
Solution 102
Conclusion 105
Conclusion 119
How to Access the Details of all The Products in a Users Basket 136
How to Add a Field to the Billing Address on the Checkout Screen 169
How to View the New Field and it’s Value on The Order Admin Screen 171
How to change an Address Field in both the Shipping and Billing Address
on the Checkout Screen 176
The Problem 176
How to Remove the Option for Users to Supply a Shipping Address 181
Checklist 206
How to Remove an Item from the Menu in the My Account Page 215
How to Show Custom Edit Screen Fields for Certain Product Types 231
How to Make Address Field Editable on the Order Admin Screen 244
Many of the chapters in this book contain code that is added via hooks and
filters, before using any of this code in anger we would recommend you read the
“do_action and add_action in WooCommerce and WordPress” and “How to
use add_filter and apply_filters in WooCommerce” chapters to get an
understanding of how actions and filters work in Wordpress/WooCommerce, as
an understanding of these concepts will underpin everything we cover in this
book.
Some chapters contain code that is not added via actions and filters, these
chapters typically deal with code you’ll use in many different scenarios, for
example finding out what products are in a users basket. If you wish to try out
any of the concepts in these chapters we suggest you take a look at the “How to
Add a PHP Page to WooCommerce” chapter which shows you how to create a
WordPress page that you can use to experiment with.
Once you have an understanding of how to use the code snippets then the book
has been written in a way that allows you to skip from chapter to chapter. So
please just go where you want to, we hope you enjoy the book :)
How to Add a Custom Field to a
Product
The Problem
Adding a custom field to a product in WooCommerce is a very popular request,
and whilst it might seem a little daunting to add a field and then get the data
entered into the field to display throughout the cart, order, and back-end order
process we can actually accomplish the task using only a few actions and filters.
The Solution
For the purposes of this solution let’s imagine we want to add a gift note field to
all products in our store, if users choose to populate the gift note field then we’ll
display it in the cart screens and the order confirmation screens on the front-end
and it will also be available to back-end users so they can create the gift notes as
specified.
function hwn_add_custom_option(){
$value = filter_input( INPUT_POST, 'gift_note' );
?>
<p>
<label for="gift_note"><?php _e( 'Gift Note:', 'hwn' ); ?>
</label><input type="text" id="gift_note" name="gift_note"
placeholder="<?php _e( 'Enter your gift note here', 'hwn' ); ?>"
value="<?php $value ?>"/>
</p>
<?php
}
add_action( 'woocommerce_before_add_to_cart_button',
'hwn_add_custom_option');
That’s all we need to do for our input to display, the gift note field should now be
showing on our shop pages as below
Limiting the Custom Field To Specific Products
We can make a change to limit the gift note field to only show for specific
products by using the $product global variable that WooCommerce makes
available to us
function hwn_add_custom_option(){
global $product;
if ( $product->get_id() !== 21 ) {
return;
}
<p>
<label for="gift_note"><?php _e( 'Gift Note:', 'hwn' ); ?>
</label><input type="text" id="gift_note" name="gift_note"
placeholder="<?php _e( 'Enter your gift note here', 'hwn' ); ?>"
value="<?php $value ?>"/>
</p>
<?php
}
add_action( 'woocommerce_before_add_to_cart_button',
'hwn_add_custom_option');
Here we check the product’s id and if it’s not 21 (which is the product id of the
polo shirt in our example) then we return from the function and no labels or input
fields are output to the screen.
You could obviously use different if logic to show the field for different products,
or groups of products.
If we didn’t want to show a text input then we could update the HTML code to
show a different type of input, providing the input we add writes a value named
“gift_note” to the pages POST collection, then it would work with the remaining
code in this article.
function hwn_add_custom_option(){
global $product;
if ( $product->get_id() !== 21 ) {
return;
}
<p>
<label for="gift_note"><?php _e( 'Gift Note:', 'hwn' ); ?>
</label>
<select id="gift_note" name="gift_note">
<option value="love_you"<?=$value == 'love_you' ? '
selected="selected"' : '';?>><?php _e( 'I love you', 'hwn' );
?></option>
<option value="thanks"<?=$value == 'thanks' ? '
selected="selected"' : '';?>><?php _e( 'Thanks!', 'hwn' );
?></option>
<option value="sorry_its_late"<?=$value ==
'sorry_its_late' ? ' selected="selected"' : '';?>><?php _e( 'Sorry
it\'s late', 'hwn' ); ?></option>
</select>
</p>
<?php
}
add_action( 'woocommerce_before_add_to_cart_button',
'hwn_add_custom_option');
Just as a side note you may have noticed the logic here
This logic will select the option that the user previously had selected prior to page
refresh, so if the user chooses “Thanks!” and then adds the product to the cart,
the “Thanks!” option will still be selected after the item has been added to the
cart.
The code also uses the PHP short tag for echo, which can look a little strange if
you’ve never seen it before, you can read more about it here.
Validating the Custom Field
This step is not required to get everything working end-to-end but if we did want
to add validation to our gift note field we can do so by hooking into the
woocommerce_add_to_cart_validation filter
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation',
'hwn_gift_note_add_to_cart_validation', 10, 3 );
● and pass a false value back to the caller to indicate the validation
has failed
● If the user has passed a valid value, then we do nothing and pass
back the $passed value, which was passed in by the code that calls
the filter
Note that this function would also prevent users from adding products directly to
the cart from the shop screen
If you wanted to allow users to continue to add products directly to the cart
without having to add a gift note then we could add a conditional check to the if
within the validation function to ensure the user is on the single product page
if ( empty( $gift_note ) ) {
return $cart_item_data;
}
$cart_item_data['gift-note'] = $gift_note;
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data',
'hwn_add_gift_note_to_cart', 10, 3 );
if ( isset( $cart_item['gift-note'] ) ){
$item_data[] = array(
'key' => __( 'Gift Note', 'hwn' ),
'display' => wc_clean($cart_item['gift-note'])
);
}
return $item_data;
}
add_filter( 'woocommerce_get_item_data',
'hwn_get_gift_note_item_data', 10, 2 );
The first thing we do in this code is to check to see if the “gift-note” key we added
via the woocommerce_add_cart_item_data is present, if it is then we add a new
key-value pair to the $item_data array with the following values
● key – this will be the name of our item, so in this case, we use the
text “Gift Note”
● display – this is the value of our item, so we pass in the “gift-note”
value from the $cart_item array
We should now see the gift note value displayed on the main cart page
if ( ! empty( $cart_item_values['gift-note'] ) ) {
$order_item->add_meta_data( __( 'Gift Note', 'hwn' ),
$cart_item_values [ 'gift-note' ]);
}
}
add_action( 'woocommerce_checkout_create_order_line_item',
'hwn_add_gift_note_to_order_line_item', 10, 3 );
The gift note value should now start to appear in all the post order screens and
emails
Here it is in the order email
I will send you an email in a couple of days with a few questions about what you
thought of the chapter. Any answers you can provide would be gratefully
received. You can also email me at [email protected] if you have any
questions or queries.
If you’d like to carry on reading you can buy the book here
https://hardworkingnerd.gumroad.com/l/EhUFrW