Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2013
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. function get_related_tag_posts_ids( $post_id, $number = 5 ) {
  2.  
  3. $related_ids = false;
  4.  
  5. $post_ids = array();
  6.  
  7. // get tag ids belonging to $post_id
  8. $tag_ids = wp_get_post_terms( $post_id, 'industry', array( 'fields' => 'ids' ) );
  9.  
  10. if ( $tag_ids ) {
  11. // get all posts that have the same tags
  12. $tag_posts = get_posts(
  13. array(
  14. 'post_type' => 'projects',
  15. 'posts_per_page' => -1, // return all posts
  16. 'no_found_rows' => true, // no need for pagination
  17. 'fields' => 'ids', // only return ids
  18. 'post__not_in' => array( $post_id ), // exclude $post_id from results
  19. 'tax_query' => array(
  20. array(
  21. 'taxonomy' => 'industry',
  22. 'field' => 'id',
  23. 'terms' => $tag_ids,
  24. 'operator' => 'IN'
  25. )
  26. )
  27. )
  28. );
  29.  
  30. // loop through posts with the same tags
  31. if ( $tag_posts ) {
  32. $score = array();
  33. $i = 0;
  34. foreach ( $tag_posts as $tag_post ) {
  35. // get tags for related post
  36. $terms = wp_get_post_terms( $tag_post, 'industry', array( 'fields' => 'ids' ) );
  37. $total_score = 0;
  38.  
  39. foreach ( $terms as $term ) {
  40. if ( in_array( $term, $tag_ids ) ) {
  41. ++$total_score;
  42. }
  43. }
  44.  
  45. if ( $total_score > 0 ) {
  46. $score[$i]['ID'] = $tag_post;
  47. // add number $i for sorting
  48. $score[$i]['score'] = array( $total_score, $i );
  49. }
  50. ++$i;
  51. }
  52.  
  53. // sort the related posts from high score to low score
  54. uasort( $score, 'sort_tag_score' );
  55. // get sorted related post ids
  56. $related_ids = wp_list_pluck( $score, 'ID' );
  57. // limit ids
  58. $related_ids = array_slice( $related_ids, 0, (int) $number );
  59. }
  60. }
  61. return $related_ids;
  62. }
  63.  
  64.  
  65. function sort_tag_score( $item1, $item2 ) {
  66. if ( $item1['score'][0] != $item2['score'][0] ) {
  67. return $item1['score'][0] < $item2['score'][0] ? 1 : -1;
  68. } else {
  69. return $item1['score'][1] < $item2['score'][1] ? -1 : 1; // ASC
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement