wc_get_related_products

Get related products based on product category and tags.

Description

(array) wc_get_related_products( (int) $product_id, (int) $limit = 5, (array) $exclude_ids = array() ); 

Returns (array)

Parameters (3)

0. $product_id (int)
The product id.
1. $limit — Optional. (int) => 5
Limit of results.
2. $exclude_ids — Optional. (array) => array()
Exclude IDs from the results.

Usage

  1. if ( !function_exists( 'wc_get_related_products' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-product-functions.php'; 
  3.  
  4. // The product id. 
  5. $product_id = -1; 
  6.  
  7. // Limit of results. 
  8. $limit = 5; 
  9.  
  10. // Exclude IDs from the results. 
  11. $exclude_ids = array(); 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = wc_get_related_products($product_id, $limit, $exclude_ids); 
  15.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-product-functions.php  
  1. function wc_get_related_products( $product_id, $limit = 5, $exclude_ids = array() ) { 
  2. global $wpdb; 
  3.  
  4. $product_id = absint( $product_id ); 
  5. $exclude_ids = array_merge( array( 0, $product_id ), $exclude_ids ); 
  6. $transient_name = 'wc_related_' . $product_id; 
  7. $related_posts = get_transient( $transient_name ); 
  8. $limit = $limit > 0 ? $limit : 5; 
  9.  
  10. // We want to query related posts if they are not cached, or we don't have enough. 
  11. if ( false === $related_posts || count( $related_posts ) < $limit ) { 
  12. $cats_array = apply_filters( 'woocommerce_product_related_posts_relate_by_category', true, $product_id ) ? apply_filters( 'woocommerce_get_related_product_cat_terms', wc_get_product_term_ids( $product_id, 'product_cat' ), $product_id ) : array(); 
  13. $tags_array = apply_filters( 'woocommerce_product_related_posts_relate_by_tag', true, $product_id ) ? apply_filters( 'woocommerce_get_related_product_tag_terms', wc_get_product_term_ids( $product_id, 'product_tag' ), $product_id ) : array(); 
  14.  
  15. // Don't bother if none are set, unless woocommerce_product_related_posts_force_display is set to true in which case all products are related. 
  16. if ( empty( $cats_array ) && empty( $tags_array ) && ! apply_filters( 'woocommerce_product_related_posts_force_display', false, $product_id ) ) { 
  17. $related_posts = array(); 
  18. } else { 
  19. $data_store = WC_Data_Store::load( 'product' ); 
  20. $related_posts = $data_store->get_related_products( $cats_array, $tags_array, $exclude_ids, $limit + 10, $product_id ); 
  21.  
  22. set_transient( $transient_name, $related_posts, DAY_IN_SECONDS ); 
  23.  
  24. shuffle( $related_posts ); 
  25.  
  26. return array_slice( $related_posts, 0, $limit );