Displaying content from one WP site on separate WP site

Yeah

$wpdb2 = new wpdb('dbuser', 'dbpassword', 'dbname', 'dbhost');

// get 10 posts, assuming the other WordPress db table prefix is "wp_"
$query = "SELECT post_title, guid FROM wp_posts
          WHERE post_status="publish"
           AND post_type="post"
          ORDER BY post_date DESC LIMIT 10";

$someposts = $wpdb2->get_results($query, OBJECT);
foreach($someposts as $somepost)
  echo "<a href=\"{$somepost->guid}\">{$somepost->post_title}</a><br />";

Another way is to use the HTTP api:

Code in your first site, where you want to display the data:

$send = array(
  'body' => array(
    'action' => 'get_some_posts',
    // send other data here, maybe a user/password if you're querying senstive data
  ),
  'user-agent' => 'RodeoRamsey; '.get_bloginfo('url')
);

$response = wp_remote_post('http://yoursiteurl.com/', $send);
  if (!is_wp_error($response) && ($response['response']['code'] == 200)) echo $response['body'];

Code in your second site, in the theme’s functions.php (or create a plugin):

add_action('template_redirect', 'process_post_request');
function process_post_request(){
  if($_POST['action'] == 'get_some_posts'):
    $posts = new WP_Query();
    $query = array('posts_per_page' => 10);
    $posts->query($query);
    while ($posts->have_posts()):
      $posts->the_post(); // here's the usual loop
      ?>

      <a href="https://wordpress.stackexchange.com/questions/7152/<?php the_permalink(); ?>"><?php the_title(); ?></a>
      <?php the_content(); ?>

      <?php
   endwhile;
   die();
  endif;
}

The 2nd method is easier and more flexible from the “formatting” perspective. For example here you could easily echo the post thumbnail as html, while using the database approach it would be very hard for you to get the link to the thumbnail image…

Leave a Comment