Categories
WordPress Tutorials

Variations as Single Products in WooCommerce

The code in this download folder displays a list of variations on the single product page which when clicked, dynamically changes the main variable product data on the single product page for each variation. The variations are displayed in columns like shop loop products using any single product page hook.

The code :

  • adds a custom loop of variations on the single variable product page
  • automatically selects the corresponding variation when clicked
  • dynamically changes the product title to match the selected variation when clicked
  • dynamically changes the price for the selected variation
  • changes the product title on variation selection

Video Demo

Shows a loop of variations created for each variable product which uses the Single Variations template.

Also shows the variations selection for the size attribute and product entry title change dynamically when any variation is clicked.

Code Installation

There’s 4 steps :

  1. Upload the file named single-variations.php and var.js to your child theme folder or templates folder.
  2. Copy and paste the PHP code from the functions.php file to the end of your child themes functions file.
  3. On your variable product edit page, select the template named Single Variations from the Post Attributes box, as seen in the demo video.
  4. Copy and paste the CSS to the end of your child themes style.css file and clear caching.

Download Folder

Related Code Snippets

Categories
Genesis Tutorials

Quantity Inventory Progress Bar for Stock Levels in WooCommerce

This code adds a progress bar for stock inventory levels to the single product page in WooCommerce.

  • The progress bar is only displayed if the Inventory > Stock Management > Track stock quantity for this product is checked.
  • The In Stock text is only shown behind the colored background of the progress bar if the stock level is greater than 20 otherwise its shown outside the colored background within the empty space of the bar.
  • The progress bar is displayed on the single product page before the add to cart button and after the single product entry title.

Demo Video

Shows the stock level in the progress bar.

Tested using the Twenty Twenty default theme for WordPress. Will work in any WordPress theme using WooCommerce.

Installation

There’s 2 steps :

  1. Add the PHP code to the end of your child themes functions file.
  2. Copy and paste the CSS to the end of your child themes style.css file and clear caching.

Download Folder

Categories
WordPress Tutorials

Show WooCommerce Variation Images in Slick Slider

This code enables you to automatically include variation featured images in a easy to customize slider, no plugins required. You can show your variation images in :

  • Any number of columns
  • With navigation arrows
  • With pagination dots below the slider
  • In any WooCommerce single product page hook position

The slider.js settings also enable you to change the number of columns at different screen widths so your slider is responsive when showing more than 1 column of variation images.

In this example, we remove the main product page image and replace it with the slider of variation images :

By default, the carousel is coded to display 3 variation images on desktops, 2 @ 768 px width and 1 @ 480 px screen width.

In this example above, we hook the carousel of variation images in below the main product image.

Demo Video

Shows the variation images hooked into the woocommerce_product_thumbnails hook as a 3 column carousel as well as a single column slider.

Installation

There’s 3 simple steps :

  1. Add the PHP code to the end of your child themes functions file.
  2. Upload the slider.js file to your child theme folder.
  3. Copy and paste the CSS to the end of your child themes style.css file and clear caching.

Download Folder

Categories
WordPress Tutorials

Use The 1st Gallery Image As The Featured Image On The Product Category Archives in WooCommerce

Rather than use the main product image as the thumbnail image on shop loop archives for categories and tags, this code enables you to use the 1st gallery image from the single product page gallery. If no gallery images exist, the main product image is used.

Demo Video

Shows the first gallery image added to the single product page displays on the product category archive replacing the main product image.

Code Installation

There’s only 1 step :

Copy and paste the code to the end of your child themes functions file or custom/functionality plugin.

Download Folder

How The Code Works

Let me explain the logic behind the modifications made to the WooCommerce product thumbnail function in this download folder :

1. Checking for Gallery Images :
The code checks if the product has gallery images. If gallery images are found, it enters a loop to handle each gallery image.

2. Getting Image URL and Srcset :
For each gallery image, it gets the image URL and the srcset attribute. This is important for responsive images.

3. Outputting Gallery Image with Link :
Each gallery image is then outputted inside an anchor (<a>) tag, linking to the product’s permalink. The src and srcset attributes are added to the image tag.

4. Fallback for Default Product Image :
If there are no gallery images, or if the loop completes, it falls back to the default behavior. For the default product image, it gets the image URL and srcset using similar functions as for the gallery images.

5. Outputting Default Product Image with Link :
The default product image is then outputted inside an anchor (<a>) tag, linking to the product’s permalink. The src and srcset attributes are added to the image tag.

6. Testing and Responsiveness :
The modification ensures that both gallery images and the default product image are responsive by including the srcset attribute, which provides different image sizes for different screen resolutions.

Categories
WordPress Tutorials

Redirect SKU from URL Directly to Specific Product Variation in WooCommerce

This code redirects a SKU from the URL directly to a specific product variation in WooCommerce. Add the code to the end of your theme’s functions.php file or in a custom functionality/code snippets plugin.

Or, you can download the file.

The PHP code uses the template_redirect action hook to check if the current page is a single product page. It then retrieves the product ID and the requested SKU from the URL. If a SKU is provided, it searches for a matching variation and redirects to the variation’s permalink.

Note: This code assumes that the SKU is passed as a query parameter in the URL (e.g., example.com/product-page/?sku=your-sku). Modify the code accordingly if your URL structure is different.

The code also works for simple products.

Related Products In Same Category

This PHP code creates a custom loop for related products in the same category as the current product being viewed on the single product page in WooCommerce. If there are less than 4 products in the same category, products in the same related tag are shown.

How The Code Works

1. Initialization of Variables :
– The function starts by initializing the $exclude array to exclude the current product ID from the query results.
– Two arrays, $tag_ids and $cat_ids, are initialized to store the term IDs of product tags and categories, respectively.

2. Retrieving Tags and Categories :
– The code retrieves the product tags and categories using get_the_terms function.
– It loops through the tags and categories, adding their term IDs to the respective arrays.

3. Determining the Taxonomy :
– The code then checks the count of categories $cat_ids and tags ($tag_ids).
– If there are more than 3 products in the same category, it sets the $taxonomy variable to ‘product_cat’ and uses the category IDs for the query.
– If there are more than 3 products using the same tag but not enough products in the same category, it sets the $taxonomy variable to ‘product_tag’ and uses the tag IDs for the query.

4. Fallback for Insufficient Categories or Tags :
– If neither condition is met (i.e., there are not enough products in the same category or tag), the code attempts to use the first category (if available) or the first tag.
– If no categories or tags are found, it echoes a message indicating that no relevant categories or tags were found.

5. WC_Product_Query :
– The code then creates a WC_Product_Query instance to query for related products.
– It specifies parameters such as the number of products to retrieve limit, order orderby and order, stock status stock_status, and the exclusion of the current product post__not_in.
– The tax query is set to filter products based on the determined taxonomy and associated terms.

This logic is designed to dynamically select whether to query related products by category or tag based on the counts of associated terms, with a fallback mechanism if there are insufficient categories or tags.

Installation

There’s only 1 step :

Copy and paste the code to the end of your child themes functions file or custom/functionality plugin.

Wholesale Discount With Price Strike Through

This code enables the storeowner to discount WooCommerce products based on the wholesale user role.

  • This code defines a function called add_wholesale_user_role using the add_role function. It creates a new user role named “wholesale” with the display name “Wholesale Customer.”
  • This code defines a function that modifies the displayed price for wholesale users.
  • It checks if the user is logged in and has the “wholesale” role using is_user_logged_in() and current_user_can( 'wholesale' ).
  • If the conditions are met, it calculates a discounted price based on a specified percentage discount.
  • The original price is displayed crossed out with the discounted price shown beside it.

Installation

There’s only 1 step :

Copy and paste the code to the end of your child themes functions file or custom/functionality plugin.

Categories
Genesis Tutorials

Add Image To Monochrome Pro Category Pages

The code in this download folder displays a image after the header in Monochrome Pro. The code includes :

  • archive template you can use on any archive page type including category and tag archives.
  • a function to add a custom media upload field to your Edit Category screens.
  • a function to display the description below your taxonomy term title.

And here’s the result :

As seen in the demo video, you have 2 options for adding unique images on each taxonomy term edit screen. You can :

  1. Install ACF and use an image field
  2. Use the custom image field added via functions.php

Download Folder

Demo Video

Shows the archive image added to the custom media upload field on the Edit Category screen using the Monochrome Pro child theme by StudioPress.

Also shows the ACF field used to add the image as an alternative solution.

Installation

There’s 4 – 5 steps depending on whether you want to use ACF.

  1. Copy and paste the PHP code from functions to your Monochrome Pro child themes functions file.
  2. Copy and paste the CSS from the style.css file to the end of your Monochrome Pro themes style sheet and clear caching.
  3. Upload the js folder to your Monochrome Pro theme folder OR upload the 2 .js files to an existing js folder.
  4. Upload the archive.php file to your Monochrome Pro theme folder. You can rename the file to category.php if you only want to use it on category archive pages.
  5. If you want use ACF to add your images, import the acf-114256.json file.

Archive Description

There’s a function named add_description between lines 113 – 124 of archive.php. Remove it if you don’t want to display a description.

Add Custom File Upload Field for Customers To Download On My Account Page in WooCommerce

This code adds a file upload field to the user profile page for WooCommerce customers. The file download link is then added to a custom tab on the my account page for each customer as seen in the following screenshots :

File Upload

In addition to adding a custom tab named ‘File Download on the “My Account” page, the code also adds a custom file upload field on the user profile.

Adding a Custom File Upload Field :

  • The code introduces a new file upload field on the user profile page within the WordPress admin interface.
  • This field is labeled ‘File Download’ and allows administrators to associate a file with each user’s profile.

Conditions for Display :

  • The file upload field is designed to be accessible only to administrators. This is achieved by checking the user’s capabilities before rendering the field.
  • If the current user has administrative capabilities (specifically, ‘manage_options’), the custom file upload field will be displayed on the user profile page.

Functionality of the File Upload Field :

  • The file upload field allows administrators to manually associate a custom file with each user’s profile.
  • When administrators navigate to a user’s profile page in the admin area, they can upload a file using the provided field.

Customization for Administrative Use :

The inclusion of the file upload field is tailored for administrative purposes, providing a way for administrators to manage custom files associated with user profiles for any customer.

File Download

The code adds a custom tab named ‘File Download’ on the WooCommerce “My Account” page and modifies the entry title for a page associated with that tab.

Adding a Custom Tab :

  • The code introduces a new tab labeled ‘File Download’ to the user account navigation menu.
  • This new tab, when clicked, should direct the user to a custom page or endpoint within the “My Account” section.

Modifying the Title of the Custom Tab Page :

  • Once the user navigates to the ‘File Download’ tab, the code modifies the title displayed on that specific page.
  • The modification involves changing the default title to a custom title such as ‘Download File.’

Conditions for Modifications :

  • The modifications are not applied globally but are conditional.
  • The code checks specific conditions to determine whether the current page corresponds to the ‘File Download’ tab page.
  • If the conditions are met, it executes the modifications; otherwise, the default behavior continues.

Code Installation

There’s only 1 step :

Copy and paste the code to the end of your child themes functions file or custom/functionality plugin.

Set Base Rate for Additional Flat Rate Shipping Fees by Any Multiple in WooCommerce

This PHP code for WooCommerce gives you the option to set a different shipping price when someone orders specific amount of products from a specific category.

For example : You are selling wine and other beverages in different categories. When a customer orders a quantity between 1 – 3 bottles of wine, we add $5 to the total shipping costs. If someone orders between 4 to 6 bottles of wine, we add $7 to the flat rate shipping costs.

In this example, the base rate for additional shipping costs is $5 and the recurring rate is $2 for every 3 additional items.

Any cost you set in the flat rate shipping method settings is also added. This setting could be zero or anything you like.

Installation

Copy and paste the code to the end of your child themes functions file or custom functionality/code snippets plugin.

Settings

  • Line 6 set your category slug or array of comma separated category slugs when targeting more than 1 product category.
  • Line 9 set your additional cost for every multiple. In this example its calculated for every 3 items.
  • Line 33 set your base cost for the 1st 3 items. In this example its set at $5.
  • Line 35 set your multiple. In this case its set at 3. $2 for every 3 items beyond the first 3.

Developers

Let’s explain the key functions in the downloadable code:

1.custom_shipping_cost_based_on_quantity_and_category Function :
– This is a custom function hooked into the woocommerce_package_rates filter.
– It calculates and modifies the shipping rates based on the quantity and category of products in the order.
– It takes two parameters: $rates (the existing shipping rates) and $package (the contents of the cart).

  1. Variables Defined :
    • $wine_category_slug: It holds the slug of the category you want to apply specific shipping rules to (e.g., ‘wine’).
    • $additional_shipping_cost_per_3_bottles: This variable represents the additional shipping cost for every 3 bottles of wine.
  2. Calculating Total Quantity :
    • The code loops through the cart contents to calculate the total quantity of products in the order.
  3. Checking for Wine Category :
    • The code checks if the specified wine category is present in the order.
  4. Modifying Flat Rate Shipping :
    • It selectively modifies the rates only for the “Flat Rate” shipping method.
    • If the wine category is present, it calculates the additional shipping cost:
      • For the first 1-3 bottles, a base cost of $5 is added.
      • For every 3 bottles beyond the first 3, an additional $2 is added for each set of 3 bottles.
  5. Returning Modified Rates:
    • The function returns the modified shipping rates.

This code allows you to customize the shipping costs based on the quantity and category of products in the cart, specifically targeting the “Flat Rate” shipping method. It ensures a base cost of $5 for the first 1 – 3 bottles and then adds $2 for every 3 bottles beyond the first 3, without capping the additional cost.

Set WooCommerce Shipping Rates Based on Quantity

To dynamically set shipping costs based on the quantity of products ordered using a WooCommerce hook, you can leverage the woocommerce_package_rates filter. in this example we :

  • Set a base shipping cost of $5 in the WooCommerce > Settings > Shipping > Shipping Methods > Flat Rate > Flat rate Settings > Cost.
  • In the code, set a base shipping cost of $10 for the first product and an additional $4 for each additional product after that.
  • Set the product category to shoes so the code only adds the additional shipping cost to products in this category and doesn’t apply the extra cost to other products in the cart from other categories.

The following screenshot shows 2 products added to the cart. Only 1 is affected by this code because it only applies to the 2nd product which is in the shoes category.

The rate set in the shipping settings is $5. The code adds another $10 for the 1st item in category shoes and then $4 per item after that. The math is as follows :

$5 set in shipping settings
$10 set in the code for the 1st item in category shoes
$4 for the 2nd item
Total = $19

  • The code works regardless of which category or categories are targeted in the code
  • and regardless of what values you enter in the shipping settings and code.
  • and applies to flat rate shipping.

Code Installation

Copy and paste the code to the end of your child themes functions file or custom functionality/code snippets plugin.

Code Settings

There’s 3 settings in the code you can swap out with your own to control which product categories are affected and values are used.

  • Line 12. Set the shipping cost for the first product. Default is 10.
  • Line 15. Set the additional shipping cost per product (after the first one). Default is 4.
  • Line 23. Set the product category slug. Default is shoes.

Add Expiration Date To Order Emails

This code adds a date picker to the Edit Product screen enabling the storeowner to add an expiration date to any single product in WooCommerce. The expiration date is then added to order emails along with the product name and date of purchase.

The date picker only displays if the checkbox is checked.

The data is then displayed on order emails like this :

Code Installation

There’s only 1 step :

Copy and paste the code to the end of your child themes functions file or custom/functionality plugin.

How The Functions Work

Certainly, let’s provide concise explanations for each function without including the code snippets:

Enqueue Datepicker Scripts and Styles

This function enqueues the jQuery UI Datepicker script and its associated CSS file, ensuring they are loaded in the WordPress admin area. Modify URLs or add additional scripts/styles as needed.

Save Custom Meta Box Data

This function saves custom meta box data for a product, checking if the “Add Expiration Date?” checkbox is checked. It saves ‘yes’ to ‘_add_expiration_date’ and the entered expiration date to ‘_expiration_date’. Modify keys or add more fields as needed.

Add Custom Fields to Product Data General Tab

This function adds custom fields (e.g., “Add Expiration Date?” checkbox and datepicker) to the Product Data General tab. Modify the structure of fields, add more, or rearrange their order based on preferences.

Display Custom Fields on Product Page

This function displays custom fields (product name, date of purchase, and expiration date) on the single product page. Customize the HTML structure or modify displayed fields based on design preferences.

Add Custom Fields to Order Email

This function adds custom fields to the order email, checking if the “Add Expiration Date?” checkbox is checked for each product. Modify displayed information or customize the HTML structure of the email.

Modifying/Extending The Code

The code snippets are modular, allowing easy modification or extension based on specific requirements.

If you need to add more fields, change labels, or adjust display logic, you can do so by understanding each function’s structure and making necessary modifications.

Always make backups and test changes in a safe environment.

Add Countdown Timer To Sales Flash

The downloadable code is a combination of PHP and jQuery used to display a countdown timer on both single products and shop loop archives in WooCommerce. This timer is commonly used in scenarios like product sales where you want to show how much time is left until a special offer ends.

The code adds a date picker on the edit product page enabling you to set a countdown date for each single product. If the date is selected and saved, the countdown timer is displayed inline with the default sales flash. If no date is chosen, the timer does not display.

Installation

There’s 3 simple steps :

1. Copy and paste the PHP code to the end of your child themes functions file or custom functionality/code snippets plugin.

2. Upload the countdown.js file to your child theme folder.

3. Copy and paste the CSS to the end of your child themes style.css file and clear caching.

Code Explanation

Here’s an explanation of each part of the code:

1. Enqueue Scripts in functions.php

This function ensures that the required scripts for jQuery, jQuery UI, and the datepicker are loaded on the front end.

  • enqueue_datepicker Function:
    • Enqueues the jQuery UI datepicker script.
    • Enqueues the jQuery UI datepicker style from the official jQuery CDN.
  • add_action Hook:
    • Hooks the enqueue_datepicker function to the wp_enqueue_scripts action.

2. Countdown Timer PHP and JavaScript in functions.php

This set of functions manages the display of a countdown timer on WooCommerce shop loop and single product pages.

  • add_countdown_timer_to_pages Function:
    • Retrieves the current product ID.
    • Gets the expiration date from the product meta using _expiration_date.
    • Checks if the expiration date is not empty.
    • Echoes HTML code containing a span with the class onsale, the text “Sale Ends:”, and a div with the class countdown-timer and a data-expiration attribute containing the expiration date.
  • add_action Hooks:
    • Hooks the add_countdown_timer_to_pages function to the woocommerce_before_shop_loop_item_title and woocommerce_product_thumbnails actions.

3. Countdown Timer JavaScript

This JavaScript code initializes the countdown timer for elements with the class countdown-timer.

  • startCountdown Function:
    • Defines the countdown logic. This function is incomplete in the provided code.
  • jQuery(document).ready Function:
    • Ensures that the code inside runs when the document is ready.
    • Initializes a countdown for each element with the class countdown-timer.
    • Calls the startCountdown function for each element, passing the element itself and the expiration date from the data-expiration attribute.

Summary:

  • The PHP functions handle the server-side logic, fetching the expiration date and outputting HTML with relevant classes and attributes.
  • JavaScript is used to initialize the countdown timer on the client side, fetching the expiration date from the data-expiration attribute and calling a function (startCountdown) to handle the countdown logic.

Shortcode to add custom fields to the product description

This code create a custom field on the single product page you can use with a shortcode to add content to page builder or block in your product description or anywhere else on the page.

Based on this question from the WooCommerce community :

Is there a way to create or add custom fields to the product description? I am using a page builder and want a little more control over where things land on the page.

Code Installation

The code from this free download can be added to the end of your child themes functions file or custom code snippets/functionality plugin.

How To Use The Shortcode

Here’s 2 screenshots showing how to use the custom field and shortcode on your single product page.

Review

Using the code? If you are using the code from this post, please leave a review.

Show The Term Description on All Paginated Pages of an Archive

This free tutorial shows you how to modify the term description for product categories and tag archives, so it displays on all pages of a paginated archive, not just the first page, which is default WooCommerce behavior.

There’s 3 simple steps we need to take to :

  1. Find the default function, in WooCommerce, which generates our product category archive description.
  2. Find the action hook, in WooCommerce, which controls the default output location of the default function.
  3. Remove the default function, modify the default function and rename it, add back the new modified custom function.

The following video explains in very simple terms, the steps you need to take to find, modify and change the default output of your archive description on your product category and tag ( taxonomy ) archive pages.

Don’t have time to learn how to modify WooCommerce code? Click the Add to Cart button and download the code for free.

Default Functions

The default function name for the term description is named woocommerce_taxonomy_archive_description.

The action hook, in WooCommerce, which controls where and when the default function executes, is named woocommerce_archive_description.

You can also see the do_action hook woocommerce_archive_description on line 44 of archive-product.php file.

Code Explanation

Lets take a deeper look into the code which we have removed from the default function for the archive description which is :

0 === absint( get_query_var( 'paged' ) )

1. get_query_var('paged') : This function retrieves the value of the specified query variable, in this case, paged. The paged variable is often used in pagination scenarios to determine which page of a set of results is being requested.

2. absint() : This function stands for “absolute integer” and is used to convert a value to its absolute integer representation. It ensures that the returned value is a non-negative integer.

3. 0 === ... : This is a comparison statement in PHP. It checks if the result of absint( get_query_var('paged') ) is identical (both in value and type) to 0.

In summary, this code checks if the absolute integer value of the paged query variable is exactly equal to 0. If it is, the whole expression will evaluate too true; otherwise, it will evaluate too false.

The purpose of this code is to check if the current page being requested is the first page in a paginated archive set for taxonomy type archive pages in WooCommerce. If paged is 0, it typically means the user is on the initial or 1st page of the archive.

Review

Using the code? If you are using the code from this post, please leave a review.

Add Free Product When Coupon Code is Applied

This PHP code adds a product to the cart when a coupon code is applied in WooCommerce. in this example, we add a free product with the id of 14646 when coupon 30OFF is applied with a 30% discount.

To create a discount code in WooCommerce that provides a percentage discount and automatically adds a specific product to the cart when the coupon is applied, you can use the coupon functionality native to WooCommerce and custom PHP code.

Here are the steps:

1. Create a Free Product :

  • In your WooCommerce dashboard, go to Products > Add New.
  • Create a new product that will be offered for free. Set the regular price to 0.

2. Create a Coupon Code :

  • Go to WooCommerce > Coupons.
  • Click on Add Coupon.

3. Configure the Coupon :

  • Set the coupon code (e.g., “30OFF”).
  • Set the discount type to Percentage Discount and enter 30 in the amount field.

4. Add Custom Code :

  • Using FTP, navigate to your child themes functions file.
  • Open the functions.php file of your child theme.
  • Add the following code at the end of the file :
  • Alternatively, use a code snippets or custom functionality plugin and add the code there instead.

Swap out 14646 with the ID of the free product you created.

5. Save Changes :

Save the changes to your functions.php file.

Review

Using the code? If you are using the code from this post, please leave a review.

Add Discount for Multiples In Item Subtotal & Cart Totals

This code enables you to set a discount for multiples, replace the original subtotal line item with the discounted subtotal and adds the discounted amount to the cart totals in WooCommerce.

You can add the multiple and discount amount on a per product basis :

Code Installation

Copy and paste to the end of your child themes functions file or custom functionality/ code snippets plugin.

How The Functions Work

  1. add_custom_fields Function:
    • Purpose: Adds custom fields to the Product Data General tab in the WooCommerce admin.
    • Explanation:
      • Uses the woocommerce_wp_text_input function to create two text input fields for the custom values (_custom_multiple_value and _custom_discount_amount).
      • The fields are displayed in the General tab of the product data section in the WooCommerce admin.
  2. save_custom_fields Function:
    • Purpose: Saves the values entered in the custom fields when a product is saved or updated.
    • Explanation:
      • Retrieves and sanitizes the values entered in the custom fields (_custom_multiple_value and _custom_discount_amount).
      • Uses the update_post_meta function to save these values for the product.
      • This ensures that the custom values are associated with each product and can be retrieved later.
  3. replace_with_discounted_subtotal Function:
    • Purpose: Modifies the cart item subtotal display in the cart based on custom conditions.
    • Explanation:
      • Retrieves the custom multiple value (_custom_multiple_value) and discount amount (_custom_discount_amount) for the current product using get_post_meta.
      • Checks if the product quantity meets the specified conditions (quantity is a multiple of the custom multiple value).
      • If conditions are met, calculates a discount based on the custom discount amount.
      • Modifies the subtotal display with a strikeout for the original subtotal and an inserted subtotal with the discount applied using sprintf.
  4. apply_custom_discount Function:
    • Purpose: Applies a custom discount to the cart based on product conditions.
    • Explanation:
      • Loops through each item in the cart using $cart->get_cart().
      • Retrieves the custom multiple value (_custom_multiple_value) and discount amount (_custom_discount_amount) for each product using get_post_meta.
      • Checks if the product quantity meets the specified conditions (quantity is a multiple of the custom multiple value).
      • If conditions are met, calculates a discount based on the custom discount amount and accumulates the total discount for all eligible products.
      • Adds a fee to the cart with the total discount amount using $cart->add_fee.
  5. WooCommerce Functions:
    • woocommerce_wp_text_input:
      • Purpose: Creates a text input field with WooCommerce styling.
      • Usage: Used in add_custom_fields to create text input fields for custom values.
    • update_post_meta:
      • Purpose: Saves metadata for a specified post.
      • Usage: Used in save_custom_fields to save the custom values (_custom_multiple_value and _custom_discount_amount) for each product.
    • get_post_meta:
      • Purpose: Retrieves the value of a specific post meta field.
      • Usage: Used in both replace_with_discounted_subtotal and apply_custom_discount to retrieve the custom multiple value and discount amount for each product.
    • wc_price:
      • Purpose: Formats a given price as a string.
      • Usage: Used in replace_with_discounted_subtotal to format the original and modified subtotals as currency strings.
    • $cart->get_cart():
      • Purpose: Retrieves an array of cart items.
      • Usage: Used in apply_custom_discount to loop through each item in the cart and perform calculations.
    • $cart->add_fee:
      • Purpose: Adds a fee to the cart.
      • Usage: Used in apply_custom_discount to add a fee with the total discount amount to the cart.

Remove the a tag ( ahref link ) from the categories list in WooCommerce

If you want to add your product category links to each product on shop loop archives, like your shop, category and tag archives, you can, using this code, with or without the link back to the category archive.

By default, this code has removed the links and only outputs the product category names.

Installation

Add the code to the end of your child themes functions file or custom functionality plugin.

Categories
Genesis Tutorials

Filter Custom Post Type Archive Using Isotope

This code uses isotope with masonry to display custom post type items in a filterable grid using Genesis. No plugins required.

In this example we create a custom post type named portfolio and custom taxonomy terms which are automatically displayed in the filter menu on creation, as seen in the demo video.

Demo Video

Shows you how to create a new CPT term and add new item to the grid using isotope in the Genesis Sample child theme by StudioPress.

  • Includes Genesis pagination.
  • Creates terms dynamically and adds them to the filters menu.
  • For use with other CPT’s, in the PHP code, search and replace all instances of portfolio with the name ( slug ) of your custom post type.

Will work in any other WordPress theme if you remove the genesis functions from the start of the archive-portfolio.php file.

Code Installation

There’s 3 simple steps :

1. Copy and paste the PHP code to the end of your child themes functions.php file. Then resave your permalinks.

2. Upload the archive-portfolio.php and iso-settings.js to your child theme folder.

3. Copy and paste the CSS to the end of your child themes style.css file and clear caching. Include the following CSS if you have many terms.

Download Code

You can then create your terms at Portfolio Items > Portfolio Types in your WordPress Dashboard.

In this case, the taxonomy terms are portfolio types, where portfolio is the custom post type :

2 Columns on Mobiles

Use this CSS to display your items in 2 columns on mobile screens :

Random Free Product For Each Day in WooCommerce

This group of 5 custom functions for WooCommerce enables you to change the price of any product for 24 hrs to free. The code includes a link you can hook in anywhere, by default the header, which display a todays free product message with a link to the single product page.

Once 24 hrs is up, the code chooses another product, changes the price to zero and displays it in the header as the dailly free product while at the same time, returning the previous days product back to it regular price so it’s no longer free.

How The Code Works

The combined functionality in this download is coded to select a random free product each day, set its price to zero, display its name in the site header ( or any other hook location ), using both the original price with a strike through and new price which is zero.

1. Selecting a Random Free Product Each Day :

  • The code uses the get_random_free_product function, which queries your WooCommerce products to find a random product. This is done using the WP_Query class.
  • The assign_random_free_product function runs on the init action hook and checks if today’s date is different from the date stored in the random_free_product_date option. If they are different, it selects a new random free product and updates the random_free_product_id and random_free_product_date options to ensure a fresh selection daily.

2. Displaying the Random Free Product Name in the Header :

  • The display_random_free_product_name function checks if a random product is assigned (via the random_free_product_id option ) and, if so, retrieves its name and product permalink.
  • It displays the product name as a link in the site header, with “Today’s Free Product” added before it. Optionally, it can also display both the original and sale prices with styling on the single product page.

3. Changing the Price to Zero for the Random Free Product :

  • To change the price of the random free product to zero everywhere, including the single product page, cart, and checkout, the change_random_free_product_price function hooks into the woocommerce_product_get_price filter. This function checks if the product is the random free product and sets the price to zero accordingly. This code ensures that the price is consistently displayed as zero in various parts of your WooCommerce site.

Installation

1. Copy all 5 code snippets to the end of your child themes functions file or custom functionality plugin.

2. Copy and paste the CSS to the end of your child themes functions file.

Scheduled Times

Instead of using the assign_random_free_product function, you can create a new function to select a random product and update it hourly, daily, or twice daily using the wp_schedule_event function.