I have two WP sites. I want to reach from one of them, into the other, and retrieve specific featured images for posts, and display them with a link to that post.

I am using this line (with the correct info for my target database):

$mydb = new wpdb('username','password','database','localhost');

What would I follow that with to retrieve and display a post thumbnail?

I am tinkering with a line of code I found elsewhere that looks like this:

$result = $mydb->get_results("select * from wp_posts where ID='1885'");

where '1885' is a sample post ID number.

In an ideal world, I would develop this to the point where it functions as a widget. The client could simply enter a post ID number from the external WP site, and the widget would retrieve the appropriate thumbnail, and display it as a link back to the appropriate post on the other site.

I am not literate at all with PHP. So far I do my best just manipulating snippets and working them into my theme templates.

3 Answers 3


Whenever I'm trying to link two sites, I find the most efficient and least destructive way is to use the WordPress XMLRPC API. http://codex.wordpress.org/XML-RPC_WordPress_API/Posts

In this case, you could pull this info through using the built in IXR_Client library. This saves a ton of time writing code and trying to mix databases. If they wind up on completely different servers at some point. You can still have this work.

It's pretty much just this...

$client = new IXR_Client(XMLRPC_URL);
$client->timeout = 1;
$req = 'wp.getPost';
$post_id = 112;
if (!$client->query( $req, $post_id, $USER, $PASS ))
    die( 'Error while creating a new post' . $client->getErrorCode() ." : ". $client->getErrorMessage());
$postcontent =  $client->getResponse();

To get the featured image of a post (e.g. the post 1885 in your example) you need to check in the wp_postmeta table the entry with the values 1885 as post_id and "_thumbnail_id" as meta_key, the value in meta_value would be the post of type "attached" (uploading a post in the media library creates a post of type attached per image file) with the info about the image file used as featured image


I did the following in my localhost environment and it worked:

$mydb = new wpdb( 'user', 'password', 'database', 'localhost' );
$query = "SELECT meta_value 
    FROM wp_postmeta 
    WHERE post_id = %d 
    AND meta_key = '_wp_attachment_metadata'
$p_id = 4;

$result = $mydb->get_row( 
    $mydb->prepare( $query, $p_id ), 
) or wp_die( "Error: query failed." );

$result_array = unserialize( $result['meta_value'] );
var_dump( $result_array );

Looks like it's not possible to get $mydb->prefix.

Also, please note the use of $wpdb->prepare when dealing with user input values.

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.