Quantcast
Channel: Question and Answer » wpdb
Viewing all articles
Browse latest Browse all 44

WPDB Multiple site's posts and get featured images

$
0
0

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?


Viewing all articles
Browse latest Browse all 44

Trending Articles