$50.00
This code creates a custom WooCommerce product loop using any WP_Query parameters. In this code:
- Action Hook Definition :
- The
custom_wc_wp_query_1
function is hooked to thewoocommerce_before_single_product
action.
- The
- 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()
.
- The function begins with a conditional check. It ensures that the function executes only if the current page is not a single product page
- 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.
- A global variable
- 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()).
- Query arguments are set for a
- WP_Query Execution :
- The
WP_Query
is executed, and the loop is initialized.
- The
- 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 usingwc_get_template_part('content', 'product')
.
- If the query returns posts, the loop begins. For each product, its ID is added to the
- Reset Post Data :
- After the loop, post data is reset using
wp_reset_postdata()
.
- After the loop, post data is reset using
- 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.
- Action hooks
- Conditional Handling for No Products :
- If the query does not return any products, an action hook
woocommerce_no_products_found
is triggered.
- If the query does not return any products, an action hook
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.