Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I running WordPress on IIS & SQL server. As some of the plugins do not work correctly with DB ABSTRACTION I am using a lot of functions.php filters as so on.

To make my search results include tags I have added the following code to my functions.php - http://pastebin.com/BZG20McY

My search results now include tags, but I get plenty of duplicated posts.

Is there any way to filter WP QUERY and remove all duplicated post before going into the WHILE LOOP?

Here is my basic loop:

<?php

$query_args = explode("&", $query_string);
$search_query = array('');

foreach($query_args as $key => $string) {
     $query_split = explode("=", $string);
     $search_query[$query_split[0]] = urldecode($query_split[1]);
} 
$search = new WP_Query($search_query);

?>


<?php if ($search->have_posts()) : ?>
     <?php while ($search->have_posts()) : $search->the_post(); ?>
          // SOME POSTS
     <?php endwhile; ?>
<?php else : ?>
// NO POSTS
<?php endif; ?>

Any suggestions much appreciated.

share|improve this question

2 Answers 2

Adding this inside the WHILE LOOP will solve the problem. It will skip the post in the loop if this post ID is present in our array (meaning, same post went through the loop before).

<?php 

    // MAKE SURE YOU DECLARE $postsIDsArray= array(); outside of the loop, on top of it
    $postID = $search->post->ID;

    // if this ID is present in the array, skip this post
    if (in_array($postID, $postsIDsArray)) continue;

    // if the ID is not present, add this ID to the array
    array_push($postsIDsArray, $postID);

?>
share|improve this answer

First simply check if we got a search query. Do this inside the pre_get_posts filter to use conditional tags. If we got a search, attach the filter.

function wpse83602_search_query( $query )
{
    if (
        ! $query->is_search()
        OR $query->is_admin
    )
        return $query;

    add_filter( 'posts_distinct', 'wpse83602_posts_distinct' );
    return $query;
}

Then just use the posts_distinct or the posts_clauses filter. Remove the filter im. to not conflict with other queries.

function wpse83602_posts_distinct( $clause )
{
    remove_filter( current_filter(), __FUNCTION__ );
    $clause[0] = "DISTINCT";
    return $clause;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.