Advertisement
Guest User

Untitled

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