How to Display Popular Products on WooCommerce Product Pages (3 Ways)

“`html
How to Display Popular Products on WooCommerce Product Pages (3 Ways)
One of the most effective ways to boost sales and engage customers on your WooCommerce store is by strategically showcasing popular products. By highlighting items that are already trending or frequently purchased, you can leverage social proof, encourage impulse buys, and guide shoppers towards making a purchase. This article will explore three practical methods for displaying popular products directly on your WooCommerce product pages. These techniques range from simple code snippets to more advanced plugin-based solutions, providing options suitable for different skill levels and website needs.
Method 1: Using Code Snippets (Simple & Direct)
This method involves directly adding code snippets to your theme’s `functions.php` file or using a code snippet plugin. It’s a lightweight approach that offers flexibility but requires some comfort level with PHP and WordPress theme customization.
Finding the Right Code Snippet
The core logic revolves around querying your WooCommerce database to identify the most popular products based on sales volume. The following snippet demonstrates a basic implementation:
“`php
4, // Number of popular products to display
‘post_type’ => ‘product’,
‘meta_key’ => ‘total_sales’,
‘orderby’ => ‘meta_value_num’,
‘order’ => ‘DESC’,
‘post__not_in’ => array( $product->get_id() ), // Exclude the current product
);
$popular_products = new WP_Query( $args );
if ( $popular_products->have_posts() ) {
echo ‘
echo ‘
You Might Also Like
‘;
echo ‘
- ‘;
- ‘;
echo ‘‘;
if($image){
echo ‘‘;
}
echo ‘‘ . esc_html( $title ) . ‘‘;
echo ‘‘;
echo ‘
while ( $popular_products->have_posts() ) {
$popular_products->the_post();
global $product;
$permalink = get_permalink();
$title = get_the_title();
$image = wp_get_attachment_image_src( get_post_thumbnail_id(), ‘woocommerce_thumbnail’ );
echo ‘
‘;
}
echo ‘
‘;
echo ‘
‘;
wp_reset_postdata();
}
}
add_action( ‘woocommerce_after_single_product_summary’, ‘display_popular_products_on_single’, 20 );
“`
Code Breakdown
- `display_popular_products_on_single()`: This function encapsulates the logic for fetching and displaying popular products.
- `is_product()`: This conditional check ensures the code only runs on single product pages.
- `$args`: This array defines the parameters for the `WP_Query` object, specifying:
- `posts_per_page`: The number of popular products to display (set to 4 in this example).
- `post_type`: The post type to query (set to ‘product’).
- `meta_key`: The meta key used to sort products (set to ‘total_sales’, which WooCommerce uses to track sales).
- `orderby`: How to order the results (set to ‘meta_value_num’ to order numerically based on ‘total_sales’).
- `order`: The order direction (set to ‘DESC’ for descending order, showing the highest sales first).
- `post__not_in`: Excludes the current product from the results to prevent displaying the same product.
- `WP_Query`: This WordPress class retrieves posts based on the provided arguments.
- The `while` loop iterates through the retrieved popular products.
- `get_permalink()`: Retrieves the URL of each product.
- `get_the_title()`: Retrieves the title of each product.
- `wp_get_attachment_image_src()`: Gets the product’s featured image.
- HTML is generated to display the product image and title with a link to the product page.
- `wp_reset_postdata()`: Resets the global `$post` object after the custom query. This is important to prevent conflicts with other parts of your website.
- `add_action()`: This function hooks the `display_popular_products_on_single()` function into the `woocommerce_after_single_product_summary` action hook, which places the output after the product summary on the single product page. The `20` specifies the priority of the action; lower numbers execute earlier.
Implementation Steps
1. **Backup Your Theme:** Before making any changes to your theme files, create a backup to prevent data loss in case of errors.
2. **Access `functions.php`:** Navigate to Appearance > Theme Editor (or Theme File Editor) in your WordPress dashboard. Locate the `functions.php` file for your active theme. *Important Note:* It’s generally recommended to use a child theme so that your changes are not overwritten when the main theme is updated.
3. **Add the Code:** Paste the code snippet into the `functions.php` file. Place it towards the end of the file, before the closing `?>` tag (if it exists).
4. **Save Changes:** Click the “Update File” button to save your changes.
5. **Test Your Product Pages:** Visit a single product page on your WooCommerce store to see if the popular products are being displayed correctly.
Customization
- **Number of Products:** Modify the `posts_per_page` value in the `$args` array to change the number of popular products displayed.
- **Image Size:** Adjust the `’woocommerce_thumbnail’` argument in `wp_get_attachment_image_src()` to use a different image size. Available options include `’thumbnail’`, `’medium’`, `’large’`, and `’full’`, or you can use a custom image size defined in your theme.
- **Location:** Change the action hook (e.g., `woocommerce_after_single_product_summary`) to display the popular products in a different location on the product page. Refer to the WooCommerce documentation for available action hooks. Other options include `woocommerce_before_single_product`, `woocommerce_product_summary`, etc. Experiment to find the best placement for your store’s design.
- **Styling:** Use CSS to style the `.popular-products` container and its contents to match your website’s design. Add your CSS to your theme’s stylesheet (usually `style.css` in your child theme) or through the WordPress Customizer (Appearance > Customize > Additional CSS).
Considerations
- **Child Theme:** Always use a child theme when modifying theme files to prevent your changes from being overwritten during theme updates.
- **Code Snippet Plugin:** If you’re not comfortable editing your theme’s `functions.php` file directly, use a code snippet plugin like “Code Snippets.” This allows you to add and manage code snippets without directly modifying theme files.
- **Performance:** While this snippet is relatively lightweight, excessive database queries can impact performance. Consider caching the results if your store has a large number of products or high traffic.
Method 2: Using Plugins (User-Friendly & Feature-Rich)
Using plugins provides a more user-friendly approach for displaying popular products, often with additional features and customization options. Numerous WooCommerce plugins cater to cross-selling, upselling, and showcasing related products, many of which can be configured to highlight popular items.
Plugin Selection
When selecting a plugin, consider the following factors:
- **Features:** Does the plugin offer the specific features you need, such as displaying products based on sales, views, or other criteria?
- **Customization Options:** Does the plugin allow you to customize the appearance and placement of the popular product display?
- **Compatibility:** Is the plugin compatible with your version of WooCommerce and WordPress? Check the plugin’s reviews and documentation for compatibility information.
- **Support:** Does the plugin developer offer good support in case you encounter any issues?
- **Reviews and Ratings:** Pay attention to user reviews and ratings to gauge the plugin’s reliability and ease of use.
Some popular WooCommerce plugins that can be used to display popular products include:
- **WooCommerce Related Products:** While primarily focused on related products, many themes can be configured to display products based on sales.
- **YITH WooCommerce Frequently Bought Together:** Suggests products that are often purchased together, indirectly highlighting popular choices.
- **UpSell, Cross-Sell & Related Products for WooCommerce – WPC Smart:** Offers comprehensive control over upselling, cross-selling, and related product displays, including options for showcasing popular products.
- **Frequently Bought Together for WooCommerce by Addify:** A powerful plugin that intelligently suggests products commonly purchased together, leveraging purchase history data to identify popular combinations.
Example: Using “UpSell, Cross-Sell & Related Products for WooCommerce – WPC Smart”
This plugin offers a flexible way to display products based on various criteria, including sales. While the setup may vary slightly depending on the plugin you choose, the general process is similar.
Installation and Activation
1. **Install the Plugin:** From your WordPress dashboard, navigate to Plugins > Add New. Search for “UpSell, Cross-Sell & Related Products for WooCommerce – WPC Smart.” Click “Install Now” and then “Activate.”
2. **Configure the Plugin:** After activation, you’ll typically find a new menu item in your WordPress dashboard (e.g., WPC). Navigate to the plugin’s settings page.
Configuration Steps
1. **Enable Upsell or Related Products:** The plugin often allows you to customize Upsell, Cross-sell, and Related product sections independently. Select the section you want to use for displaying popular products (e.g., Related Products).
2. **Define the Source:** Configure the plugin to display products based on “total sales.” Look for settings related to product selection criteria or sorting. Some plugins might directly offer an option to “Sort by Popularity” or “Sort by Sales.”
3. **Customize the Display:** Adjust the number of products to display, the layout (e.g., grid, slider), and the appearance (e.g., colors, fonts). Many plugins provide options to customize the product titles, descriptions, and add-to-cart buttons.
4. **Placement:** Choose where to display the popular products on the single product page. The plugin might offer options to insert the display before, after, or within the product summary.
5. **Save Changes:** Save your settings to apply the changes to your WooCommerce store.
Customization Options (Specific to Example Plugin)
- **Skin Options:** The plugin provides various “skins” or templates to control the visual appearance of the displayed products.
- **Number of Columns:** Adjust the number of columns to create a visually appealing grid layout.
- **Product Query:** Refine the product selection by category, tags, or other attributes. This allows you to display popular products within the same category as the viewed product.
- **Exclude Products:** Exclude specific products from being displayed (e.g., products that are out of stock or not relevant).
Advantages of Using Plugins
- **Ease of Use:** Plugins provide a user-friendly interface for managing and customizing the display of popular products without requiring code modifications.
- **Feature-Rich:** Plugins often offer advanced features such as different display layouts, product filtering, and customization options.
- **Regular Updates:** Reputable plugins are regularly updated to ensure compatibility with the latest versions of WooCommerce and WordPress.
- **Support:** Plugin developers typically provide support in case you encounter any issues.
Disadvantages of Using Plugins
- **Plugin Bloat:** Using too many plugins can slow down your website. Choose plugins carefully and only install the ones you truly need.
- **Compatibility Issues:** Plugins can sometimes conflict with each other or with your theme, leading to unexpected behavior. Always test new plugins in a staging environment before deploying them to your live site.
- **Cost:** While many plugins offer free versions, advanced features often require purchasing a premium license.
Method 3: Theme Customization (Advanced Control & Integration)
For developers or those comfortable with advanced theme customization, directly modifying your theme’s templates offers the most control over the appearance and placement of popular products. This approach requires a strong understanding of WooCommerce template structure and PHP.
Understanding WooCommerce Template Structure
WooCommerce uses a template system that allows you to override the default templates with your own custom versions. To customize the product page, you’ll typically need to modify the `single-product.php` template or its associated template parts.
The general template structure for a single product page is as follows:
- `woocommerce/single-product.php`: The main template file for displaying a single product.
- `woocommerce/content-single-product.php`: Contains the main content of the single product page.
- `woocommerce/includes/wc-template-hooks.php`: Defines the action hooks used throughout the WooCommerce templates. This file is crucial for understanding where you can insert custom content.
Overriding Templates
1. **Create a Child Theme:** Always create a child theme before modifying any theme files. This prevents your changes from being overwritten during theme updates.
2. **Copy the Template File:** Copy the `single-product.php` (or the relevant template part, such as `content-single-product.php`) from the `woocommerce` folder in the WooCommerce plugin directory to your child theme’s `woocommerce` folder. If the `woocommerce` folder doesn’t exist in your child theme, create it. The path in your child theme should mirror the path in the plugin (e.g., `your-child-theme/woocommerce/single-product.php`).
3. **Modify the Template:** Edit the copied template file in your child theme to add the code for displaying popular products.
Adding the Popular Products Code
You can use the same code snippet from Method 1 (the `display_popular_products_on_single()` function) to fetch and display popular products. The key difference is that you’ll be directly inserting the code into your theme’s template file instead of using an action hook.
1. **Locate the Insertion Point:** Identify the section of the template where you want to display the popular products. Common locations include after the product summary, before the product tabs, or within the related products section. Examine the existing HTML and PHP code to understand the structure of the template.
2. **Insert the Code:** Add the following code snippet to your template file at the desired location:
“`php
“`
Make sure that the `display_popular_products_on_single()` function is defined in your theme’s `functions.php` file (or a code snippet plugin).
Example: Adding Popular Products After the Product Summary
If you want to add the popular products after the product summary, you would modify the `content-single-product.php` file in your child theme. Locate the `woocommerce_after_single_product_summary` action hook (usually near the end of the file) and insert the `display_popular_products_on_single()` function call after it. However, it is best practice to remove the original hook added in Method 1 if you are now directly calling the function within the template.
Advantages of Theme Customization
- **Complete Control:** You have full control over the appearance and placement of the popular product display.
- **Deep Integration:** You can seamlessly integrate the popular product display into your theme’s design and layout.
- **Performance:** By carefully optimizing your code, you can potentially achieve better performance compared to using plugins.
Disadvantages of Theme Customization
- **Requires Technical Expertise:** This method requires a strong understanding of WooCommerce template structure, PHP, and HTML/CSS.
- **Maintenance Overhead:** You are responsible for maintaining the code and ensuring compatibility with future WooCommerce and WordPress updates.
- **Increased Risk of Errors:** Incorrectly modifying template files can lead to website errors or broken functionality.
Best Practices for Theme Customization
- **Use a Child Theme:** Always use a child theme to prevent your changes from being overwritten during theme updates.
- **Understand the Template Structure:** Thoroughly understand the WooCommerce template structure before making any modifications.
- **Test Thoroughly:** Test your changes thoroughly in a staging environment before deploying them to your live site.
- **Comment Your Code:** Add comments to your code to explain what it does and why you made certain decisions. This will make it easier to maintain the code in the future.
- **Use Version Control:** Use version control (e.g., Git) to track your changes and easily revert to previous versions if necessary.
By carefully considering the advantages and disadvantages of each method, you can choose the approach that best suits your technical skills, website requirements, and desired level of customization. Implementing any of these methods will help you effectively display popular products on your WooCommerce product pages, ultimately boosting sales and improving the customer experience.
“`