Custom Product Loop Using WP_Query – WooCommerce

$0.00

This code creates a custom WooCommerce product loop using any WP_Query parameters. In this code:

  1. Action Hook Definition :
    • The custom_wc_wp_query_1 function is hooked to the woocommerce_before_single_product action.
  2. Function Execution Condition :
    • The function begins with a conditional check. It ensures that the function executes only if the current page is not a single product page ! is_product() and it is not the main query ! is_main_query().
  3. Global Variable Declaration :
    • A global variable $exclude_duplicate_products is declared. This variable is likely intended to keep track of product IDs to avoid duplicates.
  4. Query Arguments :
    • Query arguments are set for a WP_Query instance. These include the post type (‘product’), the number of posts to retrieve (4), ordering by random (‘orderby’ => ‘rand’), filtering by stock status ‘stock_status’ => ‘instock’, and excluding the current product being viewed ‘post__not_in’ => array(get_queried_object_id()).
  5. WP_Query Execution :
    • The WP_Query is executed, and the loop is initialized.
  6. Loop Execution :
    • If the query returns posts, the loop begins. For each product, its ID is added to the $exclude_duplicate_products array, and the product template part is displayed using wc_get_template_part('content', 'product').
  7. Reset Post Data :
    • After the loop, post data is reset using wp_reset_postdata().
  8. Action Hooks for Shop Loop :
    • Action hooks woocommerce_product_loop_start, woocommerce_product_loop_end, woocommerce_before_shop_loop, woocommerce_after_shop_loop are triggered before and after the shop loop to allow for customization.
  9. Conditional Handling for No Products :
    • If the query does not return any products, an action hook woocommerce_no_products_found is triggered.

The purpose of this code is to display a custom loop of products before a single product page. It retrieves a set number of random in-stock products, excluding the current product being viewed, and displays them on the page. The global variable $exclude_duplicate_products is likely used to track these products to prevent duplicates. The conditional checks ensure that this behavior is limited to non-product pages and not the main query.

Installation

There’s only 1 step :

Copy & paste the PHP code ( excluding the opening PHP tag ) from the functions.php file to the end of your child themes functions file or custom functionality plugin.

You may also like…