Advertisement
vapvarun

Display custom related products on WooCommerce product pages

Dec 5th, 2023
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | Software | 0 0
  1. /**
  2. * Display custom related products on WooCommerce product pages.
  3. * Shows one product from the same category and two products from a specific 'events' category.
  4. */
  5. function wbcom_display_custom_related_products() {
  6. global $post; // Access global post object to get current product details
  7.  
  8. // Get the categories of the current product
  9. $terms = wp_get_post_terms($post->ID, 'product_cat', array('fields' => 'slugs'));
  10.  
  11. // Check if the product has categories assigned
  12. if ($terms) {
  13. $current_cat_slug = $terms[0]; // Use the first category slug as the current category
  14.  
  15. // Prepare arguments to fetch one product from the same category
  16. $args = array(
  17. 'post_type' => 'product',
  18. 'posts_per_page' => 1,
  19. 'product_cat' => $current_cat_slug,
  20. 'post__not_in' => array($post->ID) // Exclude the current product from the query
  21. );
  22.  
  23. // Prepare arguments to fetch two products from the 'events' category
  24. $events_args = array(
  25. 'post_type' => 'product',
  26. 'posts_per_page' => 2,
  27. 'product_cat' => 'events',
  28. 'post__not_in' => array($post->ID) // Exclude the current product from the query
  29. );
  30.  
  31. // Execute the queries
  32. $related_products = new WP_Query($args);
  33. $events_products = new WP_Query($events_args);
  34.  
  35. // Output products from the current category
  36. if ($related_products->have_posts()) {
  37. echo '<ul class="related-products">';
  38. while ($related_products->have_posts()) {
  39. $related_products->the_post();
  40. wc_get_template_part('content', 'product'); // Use WooCommerce template for product display
  41. }
  42.  
  43. // Output products from the 'events' category
  44. if ($events_products->have_posts()) {
  45. while ($events_products->have_posts()) {
  46. $events_products->the_post();
  47. wc_get_template_part('content', 'product'); // Use WooCommerce template for product display
  48. }
  49. }
  50. echo '</ul>';
  51. }
  52.  
  53. // Reset the WordPress query to avoid conflicts
  54. wp_reset_postdata();
  55. }
  56. }
  57.  
  58. // Call the function in the appropriate WooCommerce template file
  59. // wbcom_display_custom_related_products();
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement