Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $SEARCH_TAG__RUN = false;
- function post_tagsort($a, $b) {
- return (count($a) - count($b));
- };
- function tag_search_query($query) {
- global $wpdb, $SEARCH_TAG__RUN;
- if ( is_tag() && !$SEARCH_TAG__RUN){
- $taxquery = $sort_posts = $search_tags = $tags_connection = $myposts_id = array();
- $taxinfo = $query->tax_query->queries;
- $search_tags = $taxinfo[0]['terms'];
- $taxquery['operator'] = 'AND';
- foreach ($taxinfo[0]['terms'] as $term){
- $taxquery[] = array(
- 'taxonomy' => 'post_tag',
- 'field' => 'slug',
- 'terms' => $term
- );
- }
- $SEARCH_TAG__RUN = true;
- $args = array( 'post_type' => 'post', 'posts_per_page' => -1, 'tax_query' => $taxquery );
- $tagposts = get_posts( $args );
- foreach($tagposts as $post){
- $myposts_id[] = $post->ID;
- }
- $tags_connection = array();
- $alltags_connection = $wpdb->get_results( "SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships", ARRAY_A);
- foreach($alltags_connection as $tag){
- if(in_array($tag['object_id'], $myposts_id)){
- if($tags_connection[$tag['object_id']]['post_id'] != $tag['object_id'])
- $tags_connection[$tag['object_id']]['post_id'] = $tag['object_id'];
- $tags_connection[$tag['object_id']][] = $tag['term_taxonomy_id'];
- }
- }
- usort($tags_connection, 'post_tagsort');
- foreach($tags_connection as $t){
- $sort_posts[] = $t['post_id'];
- }
- $SEARCH_TAG__RUN = false;
- $query->set( 'post__in', $sort_posts );
- $query->set( 'orderby', 'post__in' );
- }
- return $query;
- }
- add_filter( 'pre_get_posts', 'tag_search_query' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement