/** * 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 '
'; } // Reset the WordPress query to avoid conflicts wp_reset_postdata(); } } // Call the function in the appropriate WooCommerce template file // wbcom_display_custom_related_products();