Advertisement
nefi_c

search-tag wordpress christianto wpquestions.com

Jan 18th, 2013
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.59 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.         $taxinfo = $query->tax_query->queries;
  14.         $search_tags  = $taxinfo[0]['terms'];
  15.        
  16.         $taxquery['operator'] = 'AND';
  17.         foreach ($taxinfo[0]['terms'] as $term){
  18.             $taxquery[] = array(
  19.                 'taxonomy'  =>  'post_tag',
  20.                 'field'     =>  'slug',
  21.                 'terms'     =>  $term
  22.             );
  23.         }
  24.        
  25.         $SEARCH_TAG__RUN = true;
  26.         $args = array(  'post_type' => 'post', 'posts_per_page' => -1, 'tax_query' => $taxquery );
  27.         $tagposts = get_posts( $args );
  28.         foreach($tagposts as $post){
  29.             $myposts_id[] = $post->ID;
  30.         }
  31.        
  32.         $tags_connection = array();
  33.         $alltags_connection = $wpdb->get_results( "SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships", ARRAY_A);
  34.         foreach($alltags_connection as $tag){
  35.             if(in_array($tag['object_id'], $myposts_id)){
  36.                 if($tags_connection[$tag['object_id']]['post_id'] != $tag['object_id'])
  37.                     $tags_connection[$tag['object_id']]['post_id'] = $tag['object_id'];
  38.                 $tags_connection[$tag['object_id']][] = $tag['term_taxonomy_id'];
  39.             }
  40.         }
  41.        
  42.         usort($tags_connection, 'post_tagsort');
  43.        
  44.         foreach($tags_connection as $t){
  45.             $sort_posts[] = $t['post_id'];
  46.         }  
  47.        
  48.         $SEARCH_TAG__RUN = false;  
  49.         $query->set( 'post__in', $sort_posts );
  50.         $query->set( 'orderby', 'post__in' );
  51.     }
  52.    
  53.     return $query; 
  54. }
  55. add_filter( 'pre_get_posts', 'tag_search_query' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement