1

I'm combining multiple queries for a loop using the following method:

function order_by_date( $a, $b )
{
    return strcmp( $b->post_date, $a->post_date );
}
// get the posts for the first query
$q1_args = array(
    // args for the first query 
);
$q1_posts = get_posts( $q1_args );
// get the posts for the second query
$q2_args = array(
    // args for the second query
);
$q2_posts= get_posts( $q2_args );
// Merge the post arrays together, and sort by date using the order_by_date function
$final_posts = array_merge( $q1_posts, $q2_posts );

usort( $final_posts, 'order_by_date' );
// Loop over the posts and use setup_postdata to format for template tag usage
foreach ( $final_posts as $key => $post ) {
    setup_postdata( $post ); 
    // Now we can use template tags as if this was in a normal WP loop
    the_title('<h2>','</h2>');
    the_content();
}

This works fine, but when I try to remove duplicates, I get nothing (no errors either):

// This is my code for trying to remove the duplicates
$final_posts = array_unique( array_merge( $q1_posts, $q2_posts ) );

Any ideas on what could be going wrong?

1

2 Answers 2

1

It will work with the SORT_REGULAR flag:

array_unique( array_merge( $q1_posts, $q2_posts ), SORT_REGULAR );

1
0

Thanks to Michael's answer, I used an alternative method:

Before the loop, create an array:

$do_not_duplicate = array(); // set an array for catching duplicates

Then inside the loop, add the post id to the array, and skip over it if it is already in it:

if (in_array($postID, $do_not_duplicate)) {
 continue; // if its already been through it, dont display it
 }
$do_not_duplicate[] = $postID; // add the id to the array
1
  • My answer was not optimal, so I updated it.
    – Hans
    Sep 22, 2018 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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