3

I am using the code below to query 5 Wordpress sites for their posts, merging them into an array, sorting the array by date, and then displaying them:

//SITE 1
$mydb = new wpdb('xxxx','xxxx','xxxx','localhost');
if($mydb) { 
    $query1 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish'", OBJECT); 
}
$mydb->flush(); 

//SITE 2
$mydb = new wpdb('xxxx','xxxx','xxxx','localhost');
if($mydb) { 
    $query2 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish'", OBJECT); 
}
$mydb->flush(); 

//SITE 3
$mydb = new wpdb('xxxx','xxxx','xxxx','localhost');
if($mydb) { 
    $query3 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish'", OBJECT); 
}
$mydb->flush(); 

//SITE 4
$mydb = new wpdb('xxxx','xxxx','xxxx','localhost');
if($mydb) { 
    $query4 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish'", OBJECT); 
}
$mydb->flush(); 

//SITE 5
$mydb = new wpdb('xxxx','xxxx','xxxx','localhost');
if($mydb) { 
    $query5 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish'", OBJECT); 
}
$mydb->flush(); 


//MERGE ARRAYS
$allsitearrays = array_merge($query1, $query2, $query3, $query4, $query5);


//SORT BY DATE
function cmp($a, $b) {
  if ($a->post_date == $b->post_date) {
    return 0;
  } else {
    return $a->post_date < $b->post_date ? 1 : -1; // reverse order
  }
}
usort($allsitearrays, 'cmp');



//OUTPUT
if ( $allsitearrays ):
    global $post; 
    foreach($allsitearrays as $post) {

        //OUTPUT HERE

    }
endif;

This is working great except I cannot retrieve the post's featured image with this method. I cannot use native functions like wp_get_attachment_image_src, and I feel like querying the DB again while I'm in the loop for each post to try and find it's postmeta would ultimately be overboard and have way too many queries.

Is there a way to get the postmeta of the posts I am querying in the first query, or a method I can use to avoid making so many queries?

1 Answer 1

2

This is one way how to get the postmeta of the posts, by joining the postmeta table and fetching the _wp_attached_file meta value.

Try this:

$mydb->get_results( select a.*, thumb.meta_value 
from wp_posts a 
left join (select b.post_id, c.meta_value 
from wp_postmeta b, wp_postmeta c 
where b.meta_key = '_thumbnail_id' 
and b.meta_value = c.post_id 
and c.meta_key = '_wp_attached_file') as thumb 
on thumb.post_id = a.ID 
where a.post_type = 'post' 
and a.post_status = 'publish', OBJECT );
0

Your Answer

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

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