I was recently helping a friend redesign their WordPress site and ran into a problem: we needed to display the latest posts from Site B on Site A’s homepage or sidebar, with both sites running WordPress. I initially considered using a third-party service like Wumii’s article syndication, but couldn’t resist tinkering with the code myself. Here’s how I solved it:
Method 1:
This method isn’t limited to fetching the latest posts — it can pull virtually any type of content, including most popular posts, random posts, latest comments, and more. The only downside is that it might be a bit slow.
First, create a PHP file in the root directory of the site whose posts you want to pull, and name it blog_call.php.
// Place this file in the root directory of the blog you want to pull from
define('WP_USE_THEMES', false);
require('./wp-load.php');
query_posts('showposts=10′);
// This fetches the latest posts. For popular posts, change to get_most_viewed("post",10);
// (requires a popular posts plugin). This accepts almost all wp-kit-cn code — very convenient.
?>
<?php while (have_posts()): the_post(); ?>
<li><a href="<?php the_permalink(); ?>" target="_blank"><?php echo mb_strimwidth(strip_tags(apply_filters('the_title', $post->post_title)), 0, 50," "); ?></a></li>
<?php endwhile; ?>
If you want to output post excerpts, use the following code:
// Place this file in the blog's root directory
define('WP_USE_THEMES', false);
require('./wp-load.php');
query_posts('showposts=30′);
?>
<?php while (have_posts()): the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
Finally, on the site where you want to display the articles, add the following code:
// Place this code where you want to display the article content and list
$url=http://your-blog-url/blog_call.php;
echo file_get_contents( $url );
Method 2:
This is the most straightforward approach — using WordPress’s built-in RSS functionality. Just paste the code below into the appropriate location and style it with CSS.
// Get RSS Feed(s)
include_once(ABSPATH . WPINC . '/rss.php');
$rss = fetch_rss('https://imzl.com/feed'); // Add the Feed URL of the site you want to pull from
$maxitems = 10;
$items = array_slice($rss->items, 0, $maxitems);
<ul>
if (empty($items)) echo '<li>No items</li>';
else
foreach ( $items as $item ) :
<li>
<a href='<?php echo $item['link']; ?>'
title='<?php echo $item['title']; ?>' target="_blank">
echo mb_strimwidth($item['title'] , 0, 80, '…') ;
</a>
</li>
endforeach;
</ul>
Don’t forget to add your own CSS styles.