onetone_get_related_posts

The Onetone onetone get related posts function.

Description

onetone_get_related_posts( $post_id, (int) $number_posts = -1, (string) $post_type = 'post', (string) $taxonomies = 'category' ); 

Parameters (4)

0. $post_id
The post id.
1. $number_posts — Optional. (int) => -1
The number posts.
2. $post_type — Optional. (string) => 'post'
The post type.
3. $taxonomies — Optional. (string) => 'category'
The taxonomies.

Usage

  1. if ( !function_exists( 'onetone_get_related_posts' ) ) { 
  2. require_once '/includes/theme-functions.php'; 
  3.  
  4. // The post id. 
  5. $post_id = null; 
  6.  
  7. // The number posts. 
  8. $number_posts = -1; 
  9.  
  10. // The post type. 
  11. $post_type = 'post'; 
  12.  
  13. // The taxonomies. 
  14. $taxonomies = 'category'; 
  15.  
  16. // NOTICE! Understand what this does before running. 
  17. $result = onetone_get_related_posts($post_id, $number_posts, $post_type, $taxonomies); 
  18.  

Defined (1)

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

/includes/theme-functions.php  
  1. function onetone_get_related_posts($post_id, $number_posts = -1, $post_type = 'post', $taxonomies='category') { 
  2. //$query = new WP_Query(); 
  3.  
  4. $categories = array(); 
  5.  
  6. $terms = wp_get_object_terms( $post_id, $taxonomies ); 
  7. if ( ! empty( $terms ) ) { 
  8. if ( ! is_wp_error( $terms ) ) { 
  9. foreach( $terms as $term ) { 
  10. $categories[] = $term->term_id;  
  11. if( $post_type == 'post' ) 
  12. $args = array('category__in' => $categories); 
  13. else 
  14. $args = array('tax_query' => array( 
  15. array( 
  16. 'taxonomy' => $taxonomies,  
  17. 'field' => 'term_id',  
  18. 'terms' => $categories,  
  19. ),  
  20. ), ); 
  21.  
  22. if($number_posts == 0) { 
  23. $query = new WP_Query(); 
  24. return $query; 
  25.  
  26. $args = wp_parse_args($args, array( 
  27. 'posts_per_page' => $number_posts,  
  28. 'post__not_in' => array($post_id),  
  29. 'ignore_sticky_posts' => 0,  
  30. 'meta_key' => '_thumbnail_id',  
  31. 'post_type' =>$post_type,  
  32. 'operator' => 'IN' 
  33. )); 
  34.  
  35. $query = new WP_Query($args); 
  36. wp_reset_postdata();  
  37. return $query;