nefi_c

search-tag wordpress christianto wpquestions.com

Jan 18th, 2013
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.79 KB | None | 0 0
  1. $SEARCH_TAG__RUN = false;
  2.  
  3. function post_tagsort($a, $b) {
  4.     return (count($a) - count($b));
  5. };
  6. function tag_search_query($query) {
  7.    
  8.     global $wpdb, $SEARCH_TAG__RUN;
  9.     if ( is_tag() && !$SEARCH_TAG__RUN){
  10.        
  11.         $taxquery = $sort_posts = $search_tags = $tags_connection = $myposts_id = array();
  12.  
  13.         $search_tags = explode('+',$query->query_vars['tag']);
  14.         $taxquery['operator'] = 'AND';
  15.         foreach ($search_tags as $term){
  16.             $taxquery[] = array(
  17.                 'taxonomy'  =>  'post_tag',
  18.                 'field'     =>  'slug',
  19.                 'terms'     =>  $term
  20.             );
  21.         }
  22.        
  23.         $raw_alltags = $wpdb->get_results( "SELECT term_id FROM $wpdb->term_taxonomy WHERE taxonomy = 'post_tag'", ARRAY_A);
  24.         foreach($raw_alltags as $tag){
  25.             $alltags[] = $tag['term_id'];
  26.         }
  27.  
  28.         $SEARCH_TAG__RUN = true;
  29.         $args = array(  'post_type' => 'post', 'posts_per_page' => -1, 'tax_query' => $taxquery );
  30.         $tagposts = get_posts( $args );
  31.         foreach($tagposts as $post){
  32.             $myposts_id[] = $post->ID;
  33.         }
  34.        
  35.         $tags_connection = array();
  36.         $alltags_connection = $wpdb->get_results( "SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships", ARRAY_A);
  37.         foreach($alltags_connection as $tag){
  38.             if(in_array($tag['object_id'], $myposts_id) && in_array($tag['term_taxonomy_id'], $alltags)){
  39.                 if($tags_connection[$tag['object_id']]['post_id'] != $tag['object_id'])
  40.                     $tags_connection[$tag['object_id']]['post_id'] = $tag['object_id'];
  41.                 $tags_connection[$tag['object_id']][] = $tag['term_taxonomy_id'];
  42.             }
  43.         }
  44.        
  45.         usort($tags_connection, 'post_tagsort');
  46.        
  47.         foreach($tags_connection as $t){
  48.             $sort_posts[] = $t['post_id'];
  49.         }  
  50.        
  51.         $SEARCH_TAG__RUN = false;  
  52.         $query->set( 'post__in', $sort_posts );
  53.         $query->set( 'orderby', 'post__in' );
  54.     }
  55.    
  56.     return $query; 
  57. }
  58. add_filter( 'pre_get_posts', 'tag_search_query' );
Advertisement
Add Comment
Please, Sign In to add comment