100% found this document useful (1 vote)
353 views29 pages

Learning WooCommerce Development by Example Sample

This document provides tutorials and code snippets for common WooCommerce development tasks. It covers how to add code snippets to WooCommerce via functions.php files, plugins, or directly to pages. It also discusses using do_action and add_action hooks, adding filters with add_filter, creating child themes, working with attributes, variable products, local development environments, PHP pages, product details, cart contents, checkout screens and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
353 views29 pages

Learning WooCommerce Development by Example Sample

This document provides tutorials and code snippets for common WooCommerce development tasks. It covers how to add code snippets to WooCommerce via functions.php files, plugins, or directly to pages. It also discusses using do_action and add_action hooks, adding filters with add_filter, creating child themes, working with attributes, variable products, local development environments, PHP pages, product details, cart contents, checkout screens and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Learning WooCommerce Development

By Example
How to Use This Book 14

How to add a Code Snippet to WooCommerce 16

What’s the best way to add a Code Snippet to WooCommerce? 16

Using the functions.php File in Your Theme 16

How it’s Done 17

Via the WordPress Admin Dashboard 18

Will the Editor Allow Me to Enter Bad Code? 19

Pros and Cons of Adding Snippets to the functions.php File in Your Theme
19

Using the functions.php File in Your Child Theme 20

Pros and Cons of Adding Snippets to the functions.php File in Your Child
Theme 20

Via a Third Party Plugin 21

Pros and Cons of Adding Snippets via a Third Party Plugin 23

Via a Plugin we Write Ourselves 24

Pros and Cons of Adding Snippets via a Plugin We Write Ourselves 28

Final Thoughts 29

do_action and add_action in WooCommerce and WordPress 30

Changing the order the functions are called in 32

Passing arguments to functions 33


Removing functions with remove_action 34

Why bother with do_action and add_action couldn’t we just write stuff directly to the page?
35

do_action and add_action in woocommerce 36

How to use add_filter and apply_filters in WooCommerce 37

A Contrived Example 37

Priority 39

Removing Filters 40

Passing Arguments 40

An Example from WooCommerce 43

Final Thoughts 46

How to Create a Storefront Child Theme 47

What are the Benefits of Creating a Storefront Child Theme 47

We then need to create a file in the directory called “style.css” 49

Activating the Child Theme 50

How to Upload Your Theme to a Remote Site 51

FTP 51

Upload your Child Theme as a Zip File 52

What Changes Can I Make with my Child Theme? 53


Style Changes 53

Changes via the functions.php File 54

Changes made by Altering Files 55

A Note About Enqueuing Styles 59

Is There a Way to Add Permanent CSS and Code Changes Without Creating
a Child Theme 60

How to Add Javascript to Your Child Theme 60

Understanding Attributes in Woocommerce 63

Why would you use Attributes in Woocommerce? 63

Creating Attributes in Woocommerce 63

Adding a Global Attribute 63

Adding a Custom Product Attribute 65

What’s the Point of Custom Product Attributes? 65

Filtering by Attributes in Woocommerce 66

The “Filter Products by Attribute” widget 68

Accessing Product Attributes via PHP 70

Understanding Woocommerce Variable Products 72

What are Variable Products and when should you use them? 72

How to set up a variable product 73


Categories and Attributes on a Woocommerce site 73

Categories and Attributes and Variable Products 74

How to create the variable products 77

Setting up a Woocommerce Development Environment with Local by


Flywheel and Visual Studio Code 81

Local by Flywheel 81

Visual Studio Code 86

Turning The Site into a Blueprint 92

Conclusion 94

How to Add a PHP Page to WooCommerce 95

Creating the PHP Page 95

Creating a WordPress/WooCommerce page that uses the PHP File 96

Testing the New Page 98

Final Thoughts 99

How to Detect Category and Tag Pages in Woocommerce 100

The Problem 100

The Solution 100

How to Generate Links To Categories and Tag Archives 102

Problem 102
Solution 102

Generating Links to Multiple Categories or Tags 103

Excluding Empty Categories/Tags 104

Conclusion 105

How to Add a Custom Field to a Product 106

The Problem 106

The Solution 106

Adding the Field to the Product Screen 106

Limiting the Custom Field To Specific Products 108

Showing Different Inputs 109

Validating the Custom Field 111

Adding the Gift Note to the Cart Item Data 114

Displaying the Gift Note Data in the Cart 115

Adding the Gift Note Data to an Order Line Item 117

Conclusion 119

How to Programmatically Create a Coupon 121

The Problem 121

Creating a Coupon Programmatically 121

Adding the Programmatically Created Coupon to a User’s Basket 124


The coupon_exists and cart_contains_items functions 127

How to Check a Products Type 130

The Problem 130

The Solution 130

Should I use get_type() or is_type() 131

Final Notes 131

How to Get A Products Details Using a Product Id 132

The Problem 132

Scenario 1 - We are on A Product Page, or a Page that Displays Lists of


Products 132

How do I Know if the $product Global Variable is not Available? 133

The $product global variable should be available on most customer facing


shop pages, you can check if the $product global variable has been
populated using the following code. 133

Scenario 2 - We only have Access to the Product Id 134

Final Notes 135

How to Access the Details of all The Products in a Users Basket 136

The Problem 136

The Solution 136

Different ways of writing the foreach statement 139


Dealing with Empty Carts 139

Some Example Code that Displays Cart Data 140

How to Get User Details from the Cart 142

The Problem 142

The Solution 142

How to Check If an Item Is in a User Cart 144

The Problem 144

The Solution 144

Another Solution 147

How to Add a Surcharge Based on a Custom Field 149

The Problem 149

The Solution 149

Adding Multiple Charges 151

Charging Different Fees 152

How to change Labels on the Checkout Screen 155

The Problem 155

The Solution 155

How to change Placeholders on the Checkout Screen 157

The Problem 157


The Solution 157

How to Change the Order of Fields on the Checkout Screen 160

The Problem 160

The Solution 161

How to Remove a Field on the Checkout Screen 165

The Problem 165

The Solution 165

How to Make a Field Required on the Checkout Screen 167

The Problem 167

The Solution 167

How to Add a Field to the Billing Address on the Checkout Screen 169

The Problem 169

The Solution 169

How to View the New Field and it’s Value on The Order Admin Screen 171

How to change a Shipping Address Field on the Checkout Screen 173

The Problem 173

The Solution 173

How to change an Address Field in both the Shipping and Billing Address
on the Checkout Screen 176
The Problem 176

The Solution 176

Overriding Default Fields 178

How to Remove the Option for Users to Supply a Shipping Address 181

The Problem 181

The Solution 181

Solving the Problem in Code 183

How to Add a New Field to the Checkout Screen 185

The Problem 185

The Solution 185

Validating the Field 187

Saving the Field Value 188

Showing the Field Value in the Admin Order Screen 190

How to Add a Custom Field in My Account - Account Details 194

The Problem 194

The Solution 194

How to Add an Item to the Menu in the My Account Page 198

The Problem 198

The Solution 198


Linking the New Item to a Url 200

Linking the New Item to Custom Content 201

Making sure Wordpress Can See Our New Endpoint 205

Checklist 206

Adding the New Item in a Specific Position in the Menu 207

Altering the Icon of the New Menu Item 209

How to Remove an Item from the Menu in the My Account Page 215

The Problem 215

The Solution 215

Removing Other Items from the Menu 217

Removing Items from the Menu Without Using Code 218

How to Send Custom Emails Based on Order Details 222

The Problem 222

The Solution 222

How to Add a Field to The Product Edit Screen 226

The Problem 226

Adding the Field to the Admin Page 226

Saving the Field Value 228

Using the Value in Customer Facing Pages 229


Final Notes 229

How to Show Custom Edit Screen Fields for Certain Product Types 231

The Problem 231

Limiting the Display of the Custom Field by Product Type 231

Why Won’t this Approach Work? 233

Final Notes 235

How to Access Order Details 236

The Problem 236

Scenario 1 - We have Access to the Order Object 236

Scenario 2 - We have Access to an Order Id 237

How to View All the Items in an Order 240

The Problem 240

The Solution 240

Accessing Shipping Items in the Order 241

How to Make Address Field Editable on the Order Admin Screen 244

The Problem 244

The Solution 245


How to Use This Book
Hello, and welcome to “Learning WooCommerce Development by Example” by
way of a short introduction, I just wanted to briefly go over how to use the code in
this book.

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.

In order to understand how to add code snippets to WooCommerce you should


take a look at the “How to add a Code Snippet to WooCommerce” chapter
which goes through all the ways you can add code to WooCommerce. We would
also recommend that you take a look at the “How to Create a Storefront Child
Theme” chapter to understand how child themes work.

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.

Let’s take a look at what we need to do.

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.

Adding the Field to the Product Screen


We’ll add our field using the woocommerce_before_add_to_cart_button action
hook

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');

Here’s what we’re doing in the code

● First, we check to see if the gift_note field already exists in the


pages POST variables, if it does we save the value away to a
variable named $value
● We then drop into HTML to output our input field, we use the PHP
_e function to ensure any non-user input text for the field is
translatable. We also populate the value of our input with any
previously found values that we discovered in the previous step.

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;
}

$value = filter_input( INPUT_POST, 'iconic-engraving' );


?>

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

Showing Different Inputs

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.

Here’s an example using a Select field

function hwn_add_custom_option(){
global $product;

if ( $product->get_id() !== 21 ) {
return;
}

$value = filter_input( INPUT_POST, 'iconic-engraving' );


?>

<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');

and here’s what it looks like

Just as a side note you may have noticed the logic here

<option value="love_you"<?=$value == 'love_you' ? '


selected="selected"' : '';?>><?php _e( 'I love you', 'hwn' );
?></option>

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

function hwn_gift_note_add_to_cart_validation( $passed, $product_id,


$qty ){

$value = filter_input( INPUT_POST, 'gift_note' );


if( !$value ){
$product = wc_get_product( $product_id );
wc_add_notice( sprintf( __( '%s cannot be added to the cart
until you enter a gift note.', 'hwn' ), $product->get_title() ), 'error'
);
return false;
}

return $passed;

}
add_filter( 'woocommerce_add_to_cart_validation',
'hwn_gift_note_add_to_cart_validation', 10, 3 );

Let’s step through the code

● To begin with, we use the WordPress filter_input function to see if


we have a value with the key of “gift-note” in the POST variables
● We then check to see if the value is empty (using PHP’s falsey
logic), if you wanted to use more complicated validation logic then
you could just change the if statement to suit your needs.
● If the value is empty then we retrieve the product details using the
wc_get_product WooCommerce function, note that we can’t use the
$product global variable as it is not available to us in this function.
We are aware of the product id that we need to use as
WooCommerce passes it to the filter function in the $product_id
variable
● We then use the product title to display a message telling the user
they should add a gift note

● 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

function hwn_gift_note_add_to_cart_validation( $passed,


$product_id, $qty ){

$value = filter_input( INPUT_POST, 'gift_note' );


if( !$value && is_product() ){
$product = wc_get_product( $product_id );
wc_add_notice( sprintf( __( '%s cannot be added to the
cart until you enter a gift note.', 'hwn' ), $product->get_title()
), 'error' );
return false;
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation',
'hwn_gift_note_add_to_cart_validation', 10, 3 );

Adding the Gift Note to the Cart Item Data


Now we have added the gift note field to the product page we need to intercept
the value input by the user and it to the cart item data.

We can do this by hooking into the woocommerce_add_cart_item_data filter.

function hwn_add_gift_note_to_cart( $cart_item_data, $product_id,


$variation_id ) {
$gift_note = filter_input( INPUT_POST, 'gift_note' );

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 );

Here’s what we’re doing in the function

● We firstly use PHP’s filter_input function to get the “gift-note” value


key from the POST collection, this should be the value the user
entered when adding the product to the cart
● If we can’t find a value for “gift-note” then we take no further action
and return the $cart_item_data variable unchanged
● If we do find a value then we add a key-value pair to the
$cart_item_data with the key “gift-note” and the value that was
entered into the “gift-note” field
● We now return the modified $cart_item_data and the
WooCommerce core code will add it to the cart

Displaying the Gift Note Data in the Cart


Our gift note data has now been added to the cart but it won’t display anywhere,
to get it to display in the in pre checkout screen we need to hook into the
“woocommerce_get_item_data” filter

function hwn_get_gift_note_item_data( $item_data, $cart_item ) {

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

and the mini cart


Adding the Gift Note Data to an Order Line
Item
Now the data is displaying in the cart we need to get it to display in the post order
screen, we can do this by hooking into the
woocommerce_checkout_create_order_line_item action
function hwn_add_gift_note_to_order_line_item( $order_item,
$cart_item_key, $cart_item_values ) {

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 );

In this function, we check to see if there is a “gift-note” value in the


$cart_item_values array, if there is a value then we add the data to the order item
metadata via the add_meta_data function. We pass the following values to the
function

● The name of the item, in this case, we pass “Gift Note”


● The value of the item, for this, we pass the “gift-note” value that we
have written to the cart item data in previous steps

The gift note value should now start to appear in all the post order screens and
emails
Here it is in the order email

and also in the admin “Order” screens


Conclusion
Often clients will ask for custom fields and logic to be added products in
WooCommerce stores, hopefully, the snippets above will allow you to add the
custom logic you require.
Thanks for reading this far :)

I hope you have enjoyed the sample chapter.

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

You might also like