If you build stores on a WordPress site, WooCommerce gives you a strong base, but real control comes from smart snippets. Small pieces of custom code let you shape the shop page, the checkout page, and even tiny bits of product behavior without heavy plugins. You can drop snippets in a php file, use the functions.php file in a child theme, or install a code snippets plugin for a safer, visual workflow. Many developers prefer Code Snippets or Code Snippets Pro because you can enable, disable, and export rules without touching theme files. This keeps your source code tidy and makes automatic import for new projects easy.
Snippets help with common jobs like changing the shop page title, hiding WooCommerce breadcrumbs, or tweaking checkout fields to collect the right data. You can add a custom field to a product variation, switch the cart button text, or set a minimum order amount. You can fine tune WooCommerce settings, register WooCommerce support in a theme, and enable wc product gallery zoom, wc product gallery lightbox, and wc product gallery slider in minutes.
Also, you can add a custom currency, rename a product tab to more info, or hide product categories from a widget. Whether you paste simple functions or maintain a growing library of custom code, these practical snippets give you clean functionality without bloat and they work fine across most builds when tested well.
How to Use These WooCommerce Code Snippets Safely

Adding custom snippets to WooCommerce can completely change the way your WordPress site works. But if you paste the wrong line of code into the functions.php file or make a mistake in a PHP function, the entire site can break. That is why it is important to follow safe practices when working with custom code.
Use a Child Theme or a Snippets Plugin
- Place your custom code inside the child theme’s functions.php file so it stays intact after theme updates.
- If you do not want to edit theme files directly, install a Code Snippets plugin or Code Snippets Pro.
- These tools allow you to create, manage, and export snippets without touching the theme files.
- The plugins also include options for automatic import, which makes it easier to reuse your custom snippets across different websites.
Test Before Going Live
- Never paste code directly on a live site.
- Always test your snippets on a staging environment.
- This step ensures there are no conflicts with WooCommerce settings, checkout fields, or other theme files.
Document Your Custom Code
- Add clear comments above every function explaining what it does.
- Example: whether it affects the checkout page, the shop page, WooCommerce product categories, or account checkout fields.
- Proper labeling makes it easier to understand your source code later.
Keep Backups and Version Control
- Store your snippets outside of WordPress with Git or another version control tool.
- If you use a code snippets plugin, take advantage of the export feature.
- Having a backup allows you to roll back quickly if something does not work fine after an update.
Handled the right way, snippets become a powerful toolkit. They help you customize WooCommerce without bloating your WordPress site with unnecessary plugins while keeping everything clean and stable.
Need Expert Help With WooCommerce Customization?
Seahawk’s WooCommerce development team builds custom features, manages checkout flows, and creates stable code solutions tailored for your business.
Theme and UX Setup Essentials: WooCommerce Code Snippets
Before you dive into advanced snippets, it helps to set up WooCommerce support and clean up the theme for a smoother shopping experience. Many developers overlook these basics, but they can dramatically improve how the store looks and feels for users.
Declare WooCommerce Support in Your Theme
By default, not every WordPress theme comes with full WooCommerce support. Adding it manually ensures product galleries and layouts display correctly. You can do this inside the child theme’s functions.php file or using a custom snippets plugin.
function mytheme_add_woocommerce_support() {
add_theme_support( 'woocommerce' );
add_theme_support( 'wc-product-gallery-zoom' );
add_theme_support( 'wc-product-gallery-lightbox' );
add_theme_support( 'wc-product-gallery-slider' );
}
add_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' );
This snippet adds core WooCommerce support along with wc product gallery zoom, wc product gallery lightbox, and wc product gallery slider. Together, these features improve product browsing on the single product page.
Remove WooCommerce Breadcrumbs
Breadcrumbs can be useful for navigation, but sometimes they clutter the design. If your theme already includes breadcrumbs or you prefer a cleaner header, you can remove WooCommerce breadcrumbs with this snippet:
add_action( 'init', 'remove_wc_breadcrumbs' );
function remove_wc_breadcrumbs() {
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0 );
}
Use this carefully as some stores rely on breadcrumbs for SEO value. If you are replacing them with another navigation style, removing them can simplify the design.
Replace the Shop Page Title
The default shop page title often just says “Shop.” To better align with your brand or seasonal campaigns, you can replace it with custom text.
add_filter( 'woocommerce_page_title', 'shop_page_title' );
function shop_page_title( $title ) {
if ( is_shop() ) {
return "Our Collections";
}
return $title;
}
You can rename the shop page title to match your product categories, campaigns, or brand language. For example, during holiday sales, change it to “Holiday Specials” for stronger engagement.
Catalog Tweaks That Improve Discovery
Once the basics are in place, the next step is to fine-tune your WooCommerce catalog. These snippets help you control how products and categories appear on your WordPress site, making it easier for customers to discover what they want without clutter or confusion.
Change the Default Catalog Sorting
By default, WooCommerce sorts products alphabetically or by menu order. You can change this to show the newest items first or sort by price. This small tweak can highlight fresh arrivals or best-value deals.
add_filter( 'woocommerce_default_catalog_orderby', 'custom_default_catalog_orderby' );
function custom_default_catalog_orderby() {
return 'date'; // Options: 'date', 'price', 'title'
}
This ensures shoppers see your latest products right at the top of the shop page.
Adjust the Number of Products Per Page
Too many products per page can overwhelm shoppers. Too few can frustrate them with endless clicking. Here’s how to control the product count:
add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 20 );
function new_loop_shop_per_page( $cols ) {
$cols = 12; // Adjust this number as needed
return $cols;
}
Tuning this value balances site speed with user experience.
Hide Categories or Products From Archives
Sometimes you may not want certain product categories to appear on the shop page. Seasonal items, wholesale-only products, or test categories can be excluded with a quick snippet.
add_action( 'pre_get_posts', 'remove_categories_shop' );
function remove_categories_shop( $q ) {
if ( ! $q->is_main_query() || ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'wholesale', 'seasonal' ),
'operator' => 'NOT IN'
)));
}
}
This helps keep your catalog clean by only showing the products you want customers to see.
Exclude Categories From the Product Categories Widget
If you are using the WooCommerce product categories widget in sidebars, you might not want all the products listedthere. You can exclude a category like this:
add_filter( 'woocommerce_product_categories_widget_args', 'woo_product_cat_widget_args' );
function woo_product_cat_widget_args( $cat_args ) {
$cat_args['exclude'] = array( 25 ); // Replace 25 with your category ID
return $cat_args;
}
This snippet gives you more control over product discovery and helps direct customer attention to your most profitable categories.
Product Page Enhancements That Lift Conversion: WooCommerce Code Snippets
The single product page is where shoppers decide whether to buy. With a few WooCommerce snippets, you can simplify the layout, reduce confusion, and highlight the details that matter most.
Rename or Remove Product Tabs
WooCommerce product tabs such as “Description” and “Additional Information” do not always match your store’s tone. You can rename them or remove the extra ones entirely.
add_filter( 'woocommerce_product_tabs', 'woo_rename_tab', 98 );
function woo_rename_tab( $tabs ) {
$tabs['description']['title'] = 'More Info';
return $tabs;
}
You can also remove the Additional Information tab if it feels redundant:
add_filter( 'woocommerce_product_tabs', 'remove_product_tabs', 98 );
function remove_product_tabs( $tabs ) {
unset( $tabs['additional_information'] );
return $tabs;
}
Replace “Out of Stock” With Friendlier Text
The default “Out of Stock” label can push customers away. A softer approach like “Sold” or “Coming Soon” keeps interest alive.
add_filter( 'woocommerce_get_availability', 'availability_filter_func' );
function availability_filter_func( $availability ) {
$availability['availability'] = str_ireplace( 'Out of stock', 'Sold', $availability['availability'] );
return $availability;
}
This small change can improve the customer experience without extra plugins.
Show “Already in Cart” Instead of “Add to Cart”
If a shopper has already added a product, seeing the same Add to Cart button can be confusing. This snippet replaces it with “Already in Cart.”
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );
function woo_custom_cart_button_text() {
global $woocommerce;
foreach( $woocommerce->cart->get_cart() as $cart_item ) {
if( get_the_ID() == $cart_item['product_id'] ) {
return __( 'Already in Cart', 'woocommerce' );
}
}
return __( 'Add to Cart', 'woocommerce' );
}
This provides clear feedback and makes the shopping process smoother.
Simplify Variable Product Pricing
WooCommerce normally displays ranges like $100–$200 for variable products. If you prefer to show only the minimum price with a “From” label, use this snippet:
add_filter( 'woocommerce_variable_price_html', 'variation_price_format_min', 9999, 2 );
function variation_price_format_min( $price, $product ) {
$prices = $product->get_variation_prices( true );
$min_price = current( $prices['price'] );
return sprintf( __( 'From %1$s', 'woocommerce' ), wc_price( $min_price ) );
}
This sets clearer expectations and can encourage more clicks.
Cart and Checkout Polish That Reduces Friction: WooCommerce Code Snippets
Small improvements on the cart and checkout can raise conversions fast. These snippets streamline steps, tidy forms, and keep shoppers focused.
Redirect to Checkout After Add to Cart
Use for single product funnels or flash sales where speed matters. Add to the child theme’s functions.php file or a snippets plugin.
add_filter( 'woocommerce_add_to_cart_redirect', 'seahawk_redirect_to_checkout' );
function seahawk_redirect_to_checkout( $url ) {
return wc_get_checkout_url();
}
Put Email First on Checkout
Collect email early for recovery flows and support. Lower numbers mean higher priority.
add_filter( 'woocommerce_checkout_fields', 'seahawk_email_first' );
function seahawk_email_first( $fields ) {
if ( isset( $fields['billing']['billing_email'] ) ) {
$fields['billing']['billing_email']['priority'] = 4;
}
return $fields;
}
Make Phone Optional or Required by Market
Match compliance and support needs for each region.
add_filter( 'woocommerce_billing_fields', 'seahawk_phone_requirement' );
function seahawk_phone_requirement( $address_fields ) {
// Set to true if your market needs phone required
$address_fields['billing_phone']['required'] = false;
return $address_fields;
}
Reorder or Tidy Checkout Fields
Keep forms short and logical. Example ⟶ move first and last name higher.
add_filter( 'woocommerce_checkout_fields', 'seahawk_reorder_fields' );
function seahawk_reorder_fields( $fields ) {
if ( isset( $fields['billing']['billing_first_name'] ) ) {
$fields['billing']['billing_first_name']['priority'] = 6;
}
if ( isset( $fields['billing']['billing_last_name'] ) ) {
$fields['billing']['billing_last_name']['priority'] = 8;
}
return $fields;
}
Add Custom Checkboxes Above Terms
Use for consent or extra confirmations. Includes validation.
add_action( 'woocommerce_checkout_before_terms_and_conditions', 'seahawk_checkout_checkboxes' );
function seahawk_checkout_checkboxes() {
?>
<p class="form-row custom-checkboxes">
<label class="woocommerce-form__label checkbox">
<input type="checkbox" class="woocommerce-form__input input-checkbox" name="seahawk_consent_one">
<span>I agree to receive order updates by email</span> <span class="required">*</span>
</label>
<label class="woocommerce-form__label checkbox">
<input type="checkbox" class="woocommerce-form__input input-checkbox" name="seahawk_consent_two">
<span>I confirm my shipping address is correct</span> <span class="required">*</span>
</label>
</p>
<?php
}
add_action( 'woocommerce_checkout_process', 'seahawk_checkout_checkbox_validation' );
function seahawk_checkout_checkbox_validation() {
if ( empty( $_POST['seahawk_consent_one'] ) ) {
wc_add_notice( __( 'Please accept order updates by email.' ), 'error' );
}
if ( empty( $_POST['seahawk_consent_two'] ) ) {
wc_add_notice( __( 'Please confirm your shipping address.' ), 'error' );
}
}
Limit Order Note Characters
Keep notes readable for fulfillment teams.
add_filter( 'woocommerce_checkout_fields', 'seahawk_limit_order_notes' );
function seahawk_limit_order_notes( $fields ) {
if ( isset( $fields['order']['order_comments'] ) ) {
$fields['order']['order_comments']['maxlength'] = 180;
$fields['order']['order_comments']['placeholder'] = __( 'Add short delivery notes. 180 characters max.' );
}
return $fields;
}
Show a Country Based Shipping Notice
Display a dynamic message when a specific country is selected.
add_action( 'woocommerce_before_checkout_billing_form', 'seahawk_country_notice_container' );
function seahawk_country_notice_container() {
echo '<div class="shipping-notice woocommerce-info" style="display:none">Please allow 5 to 10 business days for delivery after processing.</div>';
}
add_action( 'woocommerce_after_checkout_form', 'seahawk_country_notice_script' );
function seahawk_country_notice_script() {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
var selectEl = document.querySelector('select#billing_country');
var noticeEl = document.querySelector('.shipping-notice');
var targetCountry = 'FR';
if (!selectEl || !noticeEl) return;
function toggleNotice() {
if (selectEl.value === targetCountry) {
noticeEl.style.display = 'block';
} else {
noticeEl.style.display = 'none';
}
}
toggleNotice();
selectEl.addEventListener('change', toggleNotice);
});
</script>
<?php
}
Change Autofocus Field on Checkout
Focus the email field first for faster entry.
add_filter( 'woocommerce_checkout_fields', 'seahawk_change_autofocus' );
function seahawk_change_autofocus( $fields ) {
if ( isset( $fields['billing']['billing_first_name'] ) ) {
$fields['billing']['billing_first_name']['autofocus'] = false;
}
if ( isset( $fields['billing']['billing_email'] ) ) {
$fields['billing']['billing_email']['autofocus'] = true;
}
return $fields;
}
Add Helpful Text Near the Place Order Button
Use for privacy notes or delivery reminders.
add_action( 'woocommerce_review_order_after_submit', 'seahawk_message_below_checkout_button' );
function seahawk_message_below_checkout_button() {
echo '<p><small>By placing this order you confirm that the information provided is accurate.</small></p>';
}
Redirect Edge Cases and Validate Earlier
Keep signals clean before payment. Example ⟶ require account creation fields.
add_filter( 'woocommerce_checkout_fields', 'seahawk_require_account_fields' );
function seahawk_require_account_fields( $fields ) {
if ( isset( $fields['account']['account_username'] ) ) {
$fields['account']['account_username']['required'] = true;
}
if ( isset( $fields['account']['account_password'] ) ) {
$fields['account']['account_password']['required'] = true;
}
if ( isset( $fields['account']['account_password-2'] ) ) {
$fields['account']['account_password-2']['required'] = true;
}
return $fields;
}
Shipping Logic That Feels Smart: WooCommerce Code Snippets
Smart shipping rules reduce choice overload and make costs predictable. These snippets keep decisions simple without hiding useful options like local pickup.
Hide Paid Methods When Free Shipping Is Available
Show only free shipping when it applies. Keep rates visible if free shipping is not available.
add_filter( 'woocommerce_package_rates', 'seahawk_only_free_shipping_when_available', 10, 2 );
function seahawk_only_free_shipping_when_available( $rates, $package ) {
$new_rates = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$new_rates[ $rate_id ] = $rate;
break;
}
}
if ( ! empty( $new_rates ) ) {
// Preserve local pickup if it exists
foreach ( $rates as $rate_id => $rate ) {
if ( 'local_pickup' === $rate->method_id ) {
$new_rates[ $rate_id ] = $rate;
break;
}
}
return $new_rates;
}
return $rates;
}
Why this helps
- Removes decision fatigue when free shipping qualifies.
- Keeps local pickup for shoppers who prefer it.
- Reduces cart abandonment on price sensitive orders.
Add a Simple Free Shipping Threshold Message
If you use a subtotal rule, show a friendly notice so shoppers know how close they are.
add_action( 'woocommerce_before_cart', 'seahawk_free_shipping_threshold_notice' );
add_action( 'woocommerce_before_checkout_form', 'seahawk_free_shipping_threshold_notice' );
function seahawk_free_shipping_threshold_notice() {
$threshold = 75; // Set your free shipping threshold
$subtotal = WC()->cart ? WC()->cart->get_displayed_subtotal() : 0;
if ( $subtotal && $subtotal < $threshold ) {
$remaining = wc_price( $threshold - $subtotal );
wc_print_notice( 'Add ' . $remaining . ' more to get free shipping.', 'notice' );
}
}
Tips
- Match this threshold to your WooCommerce settings so messages stay accurate.
- Test with coupons and taxes to ensure the math reflects your policy.
Pricing and Currency Controls: WooCommerce Code Snippets
Tidy pricing builds trust. These snippets add regional currency support and clean up how prices look across your store.
Add a Custom Currency and Symbol
Useful for regional brands or test stores. Add to the child theme’s functions.php file or a snippets plugin.
// Register a custom currency code
add_filter( 'woocommerce_currencies', 'seahawk_add_currency' );
function seahawk_add_currency( $currencies ) {
$currencies['ABC'] = __( 'Sample Currency', 'woocommerce' ); // Replace ABC and name
return $currencies;
}
// Attach a symbol to your custom currency
add_filter( 'woocommerce_currency_symbol', 'seahawk_add_currency_symbol', 10, 2 );
function seahawk_add_currency_symbol( $symbol, $currency ) {
if ( 'ABC' === $currency ) {
$symbol = '¤'; // Replace with your symbol
}
return $symbol;
}
Where to use it
- WooCommerce Settings ⟶ General ⟶ Currency options.
- Select your new currency after adding the code.
Trim Useless Price Zeros
Cleaner price display improves readability.
add_filter( 'woocommerce_price_trim_zeros', '__return_true' );
What it does
- Shows 19 instead of 19.00.
- Keeps decimals only when required.
Optional ⟶ Control Price Format Per Locale
Switch the thousands and decimal separators for specific markets.
add_filter( 'wc_price_args', 'seahawk_price_args_by_locale' );
function seahawk_price_args_by_locale( $args ) {
// Example for EU style
if ( is_user_logged_in() && function_exists( 'get_user_locale' ) && 'fr_FR' === get_user_locale() ) {
$args['decimal_separator'] = ',';
$args['thousand_separator'] = ' ';
}
return $args;
}
Payments, Emails, and Order Handling: WooCommerce Code Snippets
Tighten communication and control with a few reliable snippets. These help your team see key updates, add order data to emails, pause checkout during maintenance, and block risky orders.
Add an Extra Email Recipient for Completed Orders
Loop in support or accounting when an order completes.
add_filter( 'woocommerce_email_recipient_customer_completed_order', 'seahawk_extra_completed_order_recipient', 10, 2 );
function seahawk_extra_completed_order_recipient( $recipient, $order ) {
$extra = 'ops@example.com'; // Replace with your address
if ( $recipient && strpos( $recipient, $extra ) === false ) {
$recipient .= ', ' . $extra;
}
return $recipient;
}
Tip
- For blind copy, hook into woocommerce_email_headers and add a BCC header.
Add Custom Order Meta to Transactional Emails
Show a tracking code or any saved custom field in customer emails.
// 1) Save a custom order meta field for demo purpose
add_action( 'woocommerce_checkout_update_order_meta', 'seahawk_save_tracking_meta' );
function seahawk_save_tracking_meta( $order_id ) {
// Replace with your own logic that saves a real tracking value
if ( ! metadata_exists( 'post', $order_id, '_tracking_code' ) ) {
update_post_meta( $order_id, '_tracking_code', 'ABC123' );
}
}
// 2) Inject that meta into emails
add_filter( 'woocommerce_email_order_meta_fields', 'seahawk_add_tracking_to_emails', 10, 3 );
function seahawk_add_tracking_to_emails( $fields, $sent_to_admin, $order ) {
$tracking = $order->get_meta( '_tracking_code' );
if ( $tracking ) {
$fields['tracking_code'] = array(
'label' => __( 'Tracking Code', 'woocommerce' ),
'value' => esc_html( $tracking ),
);
}
return $fields;
}
Where it shows
- Customer Processing Order
- Customer Completed Order
- Admin New Order
Deny Checkout if the User Has Pending Orders
Helpful for fraud control or special workflows. Blocks checkout when a matching customer email has pending orders.
add_action( 'woocommerce_after_checkout_validation', 'seahawk_block_when_pending_orders', 10, 2 );
function seahawk_block_when_pending_orders( $data, $errors ) {
if ( is_user_logged_in() ) {
$customer_id = get_current_user_id();
$args = array(
'type' => 'shop_order',
'status' => array( 'wc-pending' ),
'limit' => 1,
'customer_id' => $customer_id,
'return' => 'ids',
);
$pending = wc_get_orders( $args );
if ( ! empty( $pending ) ) {
$errors->add( 'seahawk_pending_block', __( 'You have a pending order. Please complete payment or cancel it before placing a new order.' ) );
}
return;
}
// Guest checkout ⟶ match by billing email
$email = isset( $data['billing_email'] ) ? sanitize_email( $data['billing_email'] ) : '';
if ( $email ) {
$args = array(
'type' => 'shop_order',
'status' => array( 'wc-pending' ),
'limit' => 1,
'billing_email' => $email,
'return' => 'ids',
);
$pending = wc_get_orders( $args );
if ( ! empty( $pending ) ) {
$errors->add( 'seahawk_pending_block_guest', __( 'You have a pending order. Please complete payment or cancel it before placing a new order.' ) );
}
}
}
Notes
- Adjust the message to match your support workflow.
- Consider allowing checkout for cash on delivery or bank transfer if needed.
Enable Holiday or Pause Mode
Keep the catalog visible while disabling cart and checkout. Perfect for maintenance windows or stock audits.
add_action( 'init', 'seahawk_holiday_mode' );
function seahawk_holiday_mode() {
if ( ! apply_filters( 'seahawk_holiday_mode_enabled', false ) ) {
return;
}
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
remove_action( 'woocommerce_checkout_order_review', 'woocommerce_checkout_payment', 20 );
add_action( 'woocommerce_before_main_content', 'seahawk_shop_disabled_notice', 5 );
add_action( 'woocommerce_before_cart', 'seahawk_shop_disabled_notice', 5 );
add_action( 'woocommerce_before_checkout_form', 'seahawk_shop_disabled_notice', 5 );
}
function seahawk_shop_disabled_notice() {
wc_print_notice( __( 'Our shop is temporarily unavailable. Please check back soon.' ), 'error' );
}
How to toggle
- Set the filter to true in a short helper snippet or via a site specific plugin:
add_filter( 'seahawk_holiday_mode_enabled', '__return_true' );
Optional ⟶ Change From Name and Address for Emails
Align email sender with your brand identity.
add_filter( 'wp_mail_from_name', 'seahawk_wp_mail_from_name', 99 );
function seahawk_wp_mail_from_name( $name ) {
$wc_name = get_option( 'woocommerce_email_from_name' );
return $wc_name ? html_entity_decode( $wc_name ) : $name;
}
add_filter( 'wp_mail_from', 'seahawk_wp_mail_from', 99 );
function seahawk_wp_mail_from( $email ) {
$wc_email = get_option( 'woocommerce_email_from' );
return $wc_email ? sanitize_email( $wc_email ) : $email;
}
Where to configure
- WooCommerce ⟶ Settings ⟶ Emails ⟶ “From” name and address.
Customer Account and Access Rules: WooCommerce Code Snippets
Account data powers support, order history, and gated content. Use these snippets to control account fields and unlock features for past buyers.
Make Account Fields Required on Checkout
Require username and passwords when you want customers to create an account at checkout.
add_filter( 'woocommerce_checkout_fields', 'seahawk_require_account_on_checkout' );
function seahawk_require_account_on_checkout( $fields ) {
if ( isset( $fields['account']['account_username'] ) ) {
$fields['account']['account_username']['required'] = true;
}
if ( isset( $fields['account']['account_password'] ) ) {
$fields['account']['account_password']['required'] = true;
}
if ( isset( $fields['account']['account_password-2'] ) ) {
$fields['account']['account_password-2']['required'] = true;
}
return $fields;
}
Good for
- Membership stores.
- Reorder support and saved addresses.
- Post purchase onboarding.
Check Whether a User Already Purchased Specific Products
Useful for unlocking downloads, limiting repeat purchases, or showing upgrade offers.
function seahawk_user_bought_any( $product_ids = array(), $user_id = 0 ) {
if ( empty( $product_ids ) ) return false;
if ( ! $user_id && is_user_logged_in() ) {
$user_id = get_current_user_id();
}
if ( ! $user_id ) return false;
$orders = wc_get_orders( array(
'type' => 'shop_order',
'status' => array( 'wc-completed', 'wc-processing' ),
'limit' => -1,
'customer_id' => $user_id,
'return' => 'ids',
) );
if ( empty( $orders ) ) return false;
foreach ( $orders as $order_id ) {
$order = wc_get_order( $order_id );
foreach ( $order->get_items() as $item ) {
$pid = $item->get_product_id();
$vid = $item->get_variation_id();
if ( in_array( $pid, $product_ids, true ) || in_array( $vid, $product_ids, true ) ) {
return true;
}
}
}
return false;
}
How to use in a template
// Example in a product template or shortcode
$unlock_for = array( 21, 67 ); // Product IDs that grant access
if ( seahawk_user_bought_any( $unlock_for ) ) {
echo '<p>Thanks for your purchase. Your bonus content is unlocked.</p>';
} else {
echo '<p>Buy the course to unlock bonus lessons.</p>';
}
Ideas
- Show a custom tab only for past buyers.
- Replace Add to Cart with a download link.
- Offer discounted upgrades to previous owners.
Search and Filter Discipline: WooCommerce Code Snippets
Control what shoppers see in search results and templates. Clean results help users find the right products faster and keep private categories hidden.
Hide a Category From On Site Search
Keep rentals, wholesale, or draft categories out of search results.
add_action( 'pre_get_posts', 'seahawk_hide_category_from_search' );
function seahawk_hide_category_from_search( $query ) {
if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
return;
}
$tax_query = array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'rentals' ), // Replace with your category slug
'operator' => 'NOT IN',
),
);
$query->set( 'post_type', array( 'product' ) );
$query->set( 'tax_query', $tax_query );
}
Use cases
- Hide wholesale only items.
- Exclude seasonal drafts until launch.
- Keep B2B bundles out of retail search.
Quick Checks for Category or Tag in Templates
Conditionally load blocks, badges, or messages based on category or tag.
// In a product loop or single template
if ( has_term( 'sneakers', 'product_cat', get_the_ID() ) ) {
echo '<span class="badge">Limited Edition</span>';
}
if ( has_term( array( 'gift', 'bundle' ), 'product_tag', get_the_ID() ) ) {
echo '<p>Ships in 24 hours</p>';
}
Ideas
- Show a “Gift Ready” badge for tagged items.
- Add size charts only to apparel categories.
- Display safety notes on cosmetic products.
Exclude Categories From the Product Categories Widget
Keep sidebars focused on what you want users to browse.
add_filter( 'woocommerce_product_categories_widget_args', 'seahawk_widget_exclude_cats' );
function seahawk_widget_exclude_cats( $args ) {
$args['exclude'] = array( 16, 25 ); // Replace with category IDs
return $args;
}
Tip
- Find IDs under Products ⟶ Categories ⟶ hover the name to see the ID in the URL.
Admin Comfort Upgrades: WooCommerce Code Snippets
Running a WooCommerce store means living in the WordPress admin. These snippets make your daily work easier by surfacing important details and aligning outgoing emails with your brand.
Add Custom Columns to the Orders List
Display extra data such as serial numbers or tracking codes directly in the order list view.
// Add a new column
add_filter( 'manage_edit-shop_order_columns', 'seahawk_edit_shop_order_columns' );
function seahawk_edit_shop_order_columns( $columns ) {
$columns['serial'] = __( 'Serial Number', 'woocommerce' );
return $columns;
}
// Fill column with data
add_action( 'manage_shop_order_posts_custom_column', 'seahawk_shop_order_column_content', 10, 2 );
function seahawk_shop_order_column_content( $column, $post_id ) {
if ( 'serial' === $column ) {
$serial = get_post_meta( $post_id, '_order_serial_number', true );
if ( $serial ) {
echo esc_html( $serial );
} else {
echo '—';
}
}
}
Why it helps
- Saves clicks by showing data upfront.
- Reduces time spent opening each order.
Add Linked Products or SKUs to Custom Post Types
If you run custom product setups, you can extend columns further.
add_filter( 'manage_edit-product_columns', 'seahawk_edit_product_columns' );
function seahawk_edit_product_columns( $columns ) {
$columns['sku'] = __( 'SKU', 'woocommerce' );
return $columns;
}
add_action( 'manage_product_posts_custom_column', 'seahawk_product_column_content', 10, 2 );
function seahawk_product_column_content( $column, $post_id ) {
if ( 'sku' === $column ) {
$product = wc_get_product( $post_id );
echo $product ? $product->get_sku() : '';
}
}
Use case
- See product SKUs at a glance.
- Keep catalog managers efficient.
Align Email Sender Name and Address With Brand
WordPress defaults can look unprofessional. Fix them by pulling values from WooCommerce settings.
add_filter( 'wp_mail_from_name', 'seahawk_custom_from_name', 99 );
function seahawk_custom_from_name( $name ) {
$wc_name = get_option( 'woocommerce_email_from_name' );
return $wc_name ? html_entity_decode( $wc_name ) : $name;
}
add_filter( 'wp_mail_from', 'seahawk_custom_from_address', 99 );
function seahawk_custom_from_address( $email ) {
$wc_email = get_option( 'woocommerce_email_from' );
return $wc_email ? sanitize_email( $wc_email ) : $email;
}
Where to set values
- WooCommerce ⟶ Settings ⟶ Emails ⟶ From name and From address.
Performance and Layout Helpers: WooCommerce Code Snippets
Faster pages and clear layouts lift conversions. These snippets help your cart look good on mobile and make featured product queries efficient.
Make the Cart Table Mobile Friendly
Turn the cart table into stacked rows on small screens. Add this CSS to your child theme stylesheet or a customizer CSS panel.
/* Mobile friendly WooCommerce cart table */
@media screen and (max-width: 700px) {
.woocommerce table.shop_table,
.woocommerce table.shop_table thead,
.woocommerce table.shop_table tbody,
.woocommerce table.shop_table th,
.woocommerce table.shop_table td,
.woocommerce table.shop_table tr {
display: block;
}
.woocommerce table.shop_table thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
.woocommerce table.shop_table tr {
margin-bottom: 12px;
border: 1px solid #e5e7eb;
border-radius: 8px;
overflow: hidden;
}
.woocommerce table.shop_table td {
position: relative;
padding-left: 50% !important;
border: none;
border-bottom: 1px solid #f1f5f9;
}
.woocommerce table.shop_table td:last-child {
border-bottom: none;
}
.woocommerce table.shop_table td::before {
position: absolute;
top: 10px;
left: 10px;
width: 45%;
white-space: nowrap;
font-weight: 600;
content: attr(data-title);
}
}
How it works
- Uses the data-title attribute WooCommerce adds to table cells.
- Hides the header and turns each row into a card.
- Improves readability on phones without a plugin.
Use a Transient for Featured Product IDs
Caching a list of featured products reduces repeated queries. Prime it once and reuse across templates.
function seahawk_get_featured_product_ids( $cache_key = 'seahawk_featured_ids', $ttl = HOUR_IN_SECONDS ) {
$ids = get_transient( $cache_key );
if ( false !== $ids ) {
return $ids;
}
$featured_query = new WP_Query( array(
'post_type' => 'product',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_featured',
'value' => 'yes',
'compare' => '=',
),
),
'fields' => 'ids',
'no_found_rows' => true,
) );
$ids = $featured_query->posts;
set_transient( $cache_key, $ids, $ttl );
return $ids;
}
// Example usage ⟶ build a mini grid
add_shortcode( 'seahawk_featured_grid', function( $atts ) {
$ids = seahawk_get_featured_product_ids();
if ( empty( $ids ) ) return '<p>No featured products found.</p>';
$out = '<ul class="featured-grid">';
foreach ( $ids as $pid ) {
$out .= '<li><a href="' . esc_url( get_permalink( $pid ) ) . '">' . esc_html( get_the_title( $pid ) ) . '</a></li>';
}
$out .= '</ul>';
return $out;
} );
Tips
- Clear the transient when you toggle featured status.
- Hook into product updates to delete the cache.
add_action( 'save_post_product', function( $post_id ) {
delete_transient( 'seahawk_featured_ids' );
} );
Compliance and Localization Details: WooCommerce Code Snippets
Small tweaks for forms and language make checkout faster and more accurate for different regions. These snippets help you localize without extra plugins.
Remove the State Field Where Not Needed
Some countries do not use states. Hiding the field shortens the form and reduces confusion.
add_filter( 'woocommerce_default_address_fields', 'seahawk_remove_state_field' );
function seahawk_remove_state_field( $fields ) {
if ( isset( $fields['state'] ) ) {
$fields['state']['required'] = false;
$fields['state']['hidden'] = true;
}
return $fields;
}
Tip
- Use conditional logic if you only want to hide it for specific countries.
Add a Custom Country to the List
Useful for test environments or special regions.
add_filter( 'woocommerce_countries', 'seahawk_add_custom_country' );
function seahawk_add_custom_country( $countries ) {
$countries['XX'] = __( 'Exampleland', 'woocommerce' ); // Replace code and name
return $countries;
}
add_filter( 'woocommerce_continents', 'seahawk_map_custom_country' );
function seahawk_map_custom_country( $continents ) {
// Add your country code to a continent
if ( isset( $continents['EU']['countries'] ) ) {
$continents['EU']['countries'][] = 'XX';
}
return $continents;
}
Where it appears
- WooCommerce Settings ⟶ General ⟶ Selling locations.
- Country dropdowns on checkout and account pages.
Quickly Translate Microcopy With gettext
Fix typos or switch wording across the store without editing templates.
add_filter( 'gettext', 'seahawk_quick_translate', 10, 3 );
function seahawk_quick_translate( $translated, $original, $domain ) {
// Example ⟶ change “Choose an option” to “Select”
if ( 'Choose an option' === $original && 'woocommerce' === $domain ) {
return 'Select';
}
// Example ⟶ rename “Add to cart” to “Add to Bag”
if ( 'Add to cart' === $original && 'woocommerce' === $domain ) {
return 'Add to Bag';
}
return $translated;
}
Notes
- Match the original string exactly.
- Keep changes consistent with your brand voice.
Optional ⟶ Localize Price Separators by Locale
Help users read prices in a familiar format.
add_filter( 'wc_price_args', 'seahawk_price_format_by_locale' );
function seahawk_price_format_by_locale( $args ) {
if ( function_exists( 'get_user_locale' ) && 'fr_FR' === get_user_locale() ) {
$args['decimal_separator'] = ',';
$args['thousand_separator'] = ' ';
}
return $args;
}
Test
- Cart totals.
- Coupons and taxes.
- Order emails.
Final Thoughts
You now have a library of WooCommerce code snippets that cover catalog display, checkout flow, shipping logic, pricing, localization, and admin comfort. Used together, they give you control without heavy plugins and keep your WordPress site lean.
Before you roll them out, keep these last best practices in mind:
- Always test in staging before applying snippets to a live site.
- Keep backups of your functions.php file or snippets plugin export.
- Add comments to every snippet so future developers understand what each one does.
- Review WooCommerce updates ⟶ some snippets may need adjustments over time.
Handled with care, these small functions can save you dozens of plugin installs and make your online store faster and easier to manage.
FAQs about WooCommerce Code Snippets
What is the safest way to add WooCommerce snippets?
The safest way is to use a child theme’s functions.php file or a Code Snippets plugin. This ensures your code remains intact during theme updates and can be managed without editing theme files directly.
Should I use functions.php or a snippets plugin?
If you want full control, functions.php works. For flexibility, especially on client sites, a plugin like Code Snippets Pro is easier to manage and offers automatic import and export.
Can I break my site with a bad snippet?
Yes. A single PHP error can cause a fatal error. Always test snippets on a staging site before adding them to a live store.
Do snippets slow down WooCommerce?
No, not if written correctly. In fact, snippets often replace plugins, which reduces bloat and speeds up your store.
How do I test snippets after adding them?
Test as both a guest and logged-in user. Go through the cart, checkout page, and account checkout fields. Confirm shipping, payment method, and totals still work correctly.