
How to Show Products From Same Taxonomy Term As Single Product in WooCommerce
Displaying related products on your e-commerce site is crucial for boosting sales and increasing user engagement. In this blog post, we will discuss how to show products from the same taxonomy term as a single product in WooCommerce. With this approach, you can provide a better shopping experience by offering relevant product recommendations based on categories or tags. Let’s dive into the details and learn how to create a custom plugin for this purpose.
Our Custom WordPress Plugin to Show Products From Same Taxonomy Term As Single Product in WooCommerce
This is our custom-built plugin for our readers. Licensed in GPL, you are free to use it for both personal and commercial applications.
<?php
/**
* Plugin Name: Same Taxonomy Term Products
* Description: A custom plugin to display products from the same taxonomy term as a single product in WooCommerce.
* Version: 1.0.0
* Author: ShieldThemes
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: same-taxonomy-term-products
*/
// Prevent direct access to the file
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
// Check if the class doesn't already exist
if ( ! class_exists( 'Same_Taxonomy_Term_Products' ) ) :
class Same_Taxonomy_Term_Products {
// Constructor function to initialize the class
public function __construct() {
// Hook to display related products after the single product summary
add_action( 'woocommerce_after_single_product_summary', array( $this, 'display_same_taxonomy_term_products' ), 25 );
}
/**
* Display products from the same taxonomy term as a single product in WooCommerce.
*/
public function display_same_taxonomy_term_products() {
// Get the global $product variable
global $product;
// If $product is not an instance of WC_Product, return
if ( ! $product instanceof WC_Product ) {
return;
}
// Get taxonomy terms for the current product
$taxonomy_terms = $this->get_product_taxonomy_terms( $product->get_id() );
// If there are no taxonomy terms, return
if ( empty( $taxonomy_terms ) ) {
return;
}
// Get the query arguments for WP_Query
$args = $this->get_query_args( $product->get_id(), $taxonomy_terms );
// Create a new WP_Query instance with the query arguments
$products = new WP_Query( $args );
// If the query has posts, display them in a loop
if ( $products->have_posts() ) {
// Start the WooCommerce product loop
woocommerce_product_loop_start();
// Iterate through the products and display each one
while ( $products->have_posts() ) {
// Set up the post data for the current product
$products->the_post();
// Get the template part for displaying a product
wc_get_template_part( 'content', 'product' );
}
// End the WooCommerce product loop
woocommerce_product_loop_end();
// Reset the WooCommerce loop
woocommerce_reset_loop();
// Reset the post data
wp_reset_postdata();
}
}
/**
* Get taxonomy terms for the given product ID.
*
* @param int $product_id
* @return array
*/
protected function get_product_taxonomy_terms( $product_id ) {
// Define the taxonomies to get terms from
$taxonomies = array( 'product_cat', 'product_tag' );
// Get the terms for the product from the specified taxonomies
$terms = wp_get_object_terms( $product_id, $taxonomies, array( 'fields' => 'ids' ) );
// If there's no error, return the terms, otherwise return an empty array
return ! is_wp_error( $terms ) ? $terms : array();
}
/**
* Get query arguments for WP_Query.
*
* @param int $product_id
* @param array $taxonomy_terms
* @return array
*/
protected function get_query_args( $product_id, $taxonomy_terms ) {
// Define the arguments for the WP_Query to retrieve products from the same taxonomy terms
$args = array(
'post_type' => 'product', // Set the post type to 'product'
'post_status' => 'publish', // Get only published products
'posts_per_page' => 4, // Limit the number of products to display
'post__not_in' => array( $product_id ), // Exclude the current product from the query
'ignore_sticky_posts' => 1, // Ignore sticky posts
'tax_query' => array( // Define the taxonomy query
'relation' => 'OR', // Show products that match any of the taxonomy terms
array(
'taxonomy' => 'product_cat', // Set the taxonomy to 'product_cat' (product categories)
'field' => 'term_id', // Match products by term ID
'terms' => $taxonomy_terms, // Set the terms to match
),
array(
'taxonomy' => 'product_tag', // Set the taxonomy to 'product_tag' (product tags)
'field' => 'term_id', // Match products by term ID
'terms' => $taxonomy_terms, // Set the terms to match
),
),
);
// Return the query arguments
return $args;
}
}
// Create a new instance of the Same_Taxonomy_Term_Products class
new Same_Taxonomy_Term_Products();
endif;
How the Plugin Works
Our custom plugin hooks into the WooCommerce woocommerce_after_single_product_summary
action to display related products. It queries products from the same taxonomy terms (categories or tags) as the current single product and displays them on the product page. The plugin is designed to be performance-optimized and well-documented, ensuring smooth integration with your WooCommerce store.
Understanding the Code
In this section, we will delve deeper into the code to understand each variable and function in greater detail.
class Same_Taxonomy_Term_Products
: This class encapsulates all the plugin’s functionality. By using a class, we keep the code organized and easy to manage, ensuring that the plugin is maintainable and scalable.
__construct()
: The constructor function initializes the plugin by hooking the display_same_taxonomy_term_products
method to the woocommerce_after_single_product_summary
action. This ensures that our related products are displayed right after the single product summary on the product page.
display_same_taxonomy_term_products()
: This function is responsible for displaying the related products from the same taxonomy term as the current single product. It follows these steps:
- Check if the global
$product
variable is an instance ofWC_Product
. This ensures that we’re working with a valid WooCommerce product object. - Retrieve the taxonomy terms for the current product using the
get_product_taxonomy_terms()
function. If there are no taxonomy terms, the function returns early without displaying any related products. - Call the
get_query_args()
function to set up the query arguments for fetching related products from the same taxonomy terms. - Create a new
WP_Query
object with the arguments obtained in the previous step, fetching the related products. - If there are related products, use the WooCommerce product loop (
woocommerce_product_loop_start()
,wc_get_template_part()
,woocommerce_product_loop_end()
) to display the related products in a consistent format with the rest of your WooCommerce store.
get_product_taxonomy_terms($product_id)
: This function accepts the product ID as an argument and returns the taxonomy terms (categories and tags) associated with the product. It follows these steps:
- Define the
$taxonomies
variable as an array containing the taxonomy names, ‘product_cat’ and ‘product_tag’, used to get the product terms. - Use
wp_get_object_terms()
to get the terms associated with the product. This function accepts the product ID, taxonomies, and an array of arguments specifying the format of the returned terms (in this case, only term IDs). - Check if
wp_get_object_terms()
returned aWP_Error
object. If not, return the taxonomy terms array; otherwise, return an empty array.
get_query_args($product_id, $taxonomy_terms)
: This function accepts the product ID and taxonomy terms as arguments and returns the arguments for WP_Query
. It follows these steps:
- Define the
$args
variable as an array of query arguments. Set thepost_type
to ‘product’,post_status
to ‘publish’, andposts_per_page
to the desired number of related products (in this case, 4). - Exclude the current single product from the query by setting the
post__not_in
argument to an array containing the product ID. - Ignore sticky posts by setting the
ignore_sticky_posts
argument to 1. - Set up the
tax_query
the argument to fetch products from the same taxonomy terms. Use the ‘OR’ relation to include products from any of the specified taxonomy terms (categories or tags). Define two separate arrays for ‘product_cat’ and ‘product_tag’ taxonomies, setting the ‘field’ to ‘term_id’ and ‘terms’ to the$taxonomy_terms
variable.
$taxonomies
: This variable holds an array containing the taxonomy names, ‘product_cat’ and ‘product_tag’, used to get the product terms in the get_product_taxonomy_terms()
function. It helps in fetching the terms associated with the product from both categories and tags.
$terms
: This variable holds an array of taxonomy term IDs associated with the product. It is used in the get_query_args()
function to set up the tax_query
argument, which helps fetch the related products from the same taxonomy terms.
$args
: This variable holds an array of arguments for WP_Query
, which is used to fetch products from the same taxonomy terms. It includes arguments like post_type
, post_status
, posts_per_page
, post__not_in
, ignore_sticky_posts
, and tax_query
. By customizing these arguments, you can modify the related product query to match your specific requirements.
$products
: This variable holds a new WP_Query
object, which is used to fetch the related products based on the arguments provided by the $args
variable. The WP_Query
the object is used to interact with the WordPress database and retrieve the desired products that match the specified taxonomy terms.
After understanding the purpose and functionality of each variable and function, it’s essential to recognize how they work together to achieve the desired output. The display_same_taxonomy_term_products()
function serves as the primary entry point, calling other functions and using their output to display the related products on the single product page. By structuring the code in a modular fashion, we ensure that it is maintainable, scalable, and easy to understand.
Final Conclusion
In conclusion, this custom plugin enables you to show products from the same taxonomy term as a single product in WooCommerce. By offering relevant product recommendations based on categories or tags, you can enhance user engagement, improve conversion rates, and increase sales on your e-commerce site. This detailed understanding of the code will help you tailor the plugin to your specific needs and optimize it for your WooCommerce store.
Written by Team