/**
* Display custom related products on WooCommerce product pages.
* Shows one product from the same category and two products from a specific 'events' category.
*/
function wbcom_display_custom_related_products() {
global $post; // Access global post object to get current product details
// Get the categories of the current product
$terms = wp_get_post_terms($post->ID, 'product_cat', array('fields' => 'slugs'));
// Check if the product has categories assigned
if ($terms) {
$current_cat_slug = $terms[0]; // Use the first category slug as the current category
// Prepare arguments to fetch one product from the same category
$args = array(
'post_type' => 'product',
'posts_per_page' => 1,
'product_cat' => $current_cat_slug,
'post__not_in' => array($post->ID) // Exclude the current product from the query
);
// Prepare arguments to fetch two products from the 'events' category
$events_args = array(
'post_type' => 'product',
'posts_per_page' => 2,
'product_cat' => 'events',
'post__not_in' => array($post->ID) // Exclude the current product from the query
);
// Execute the queries
$related_products = new WP_Query($args);
$events_products = new WP_Query($events_args);
// Output products from the current category
if ($related_products->have_posts()) {
echo '<ul class="related-products">';
while ($related_products->have_posts()) {
$related_products->the_post();
wc_get_template_part('content', 'product'); // Use WooCommerce template for product display
}
// Output products from the 'events' category
if ($events_products->have_posts()) {
while ($events_products->have_posts()) {
$events_products->the_post();
wc_get_template_part('content', 'product'); // Use WooCommerce template for product display
}
}
echo '</ul>';
}
// Reset the WordPress query to avoid conflicts
wp_reset_postdata();
}
}
// Call the function in the appropriate WooCommerce template file
// wbcom_display_custom_related_products();
Comments