I am trying to get the 2 latest posts from my personal website, using the code below from http://codex.wordpress.org/Function_Reference/fetch_feed#Usage
<h2><?php _e( 'Recent news from Some-Other Blog:', 'my-text-domain' ); ?></h2>
<?php // Get RSS Feed(s)
include_once( ABSPATH . WPINC . '/feed.php' );
// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed( 'THISISWHEREMYURLGOES/' );
$maxitems = 0;
if ( ! is_wp_error( $rss ) ) : // Checks that the object is created correctly
// Figure out how many total items there are, but limit it to 5.
$maxitems = $rss->get_item_quantity( 2 );
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $rss->get_items( 0, $maxitems );
endif;
?>
<ul>
<?php if ( $maxitems == 0 ) : ?>
<li><?php _e( 'No items', 'my-text-domain' ); ?></li>
<?php else : ?>
<?php // Loop through each feed item and display each item as a hyperlink. ?>
<?php foreach ( $rss_items as $item ) : ?>
<?php echo esc_html( $item->get_title() ); ?>
<li>
<a href="<?php echo esc_url( $item->get_permalink() ); ?>"
title="<?php printf( __( 'Posted %s', 'my-text-domain' ), $item->get_date('j F Y | g:i a') ); ?>">
<?php echo esc_html( $item->get_title() ); ?>
<?php printf( __( 'Posted %s', 'my-text-domain' ), $item->get_date('j F Y | g:i a') ); ?>
</a>
</li>
<?php endforeach; ?>
<?php endif; ?>
With this code, I can get the Posts URL, the title and the date posted, which is great!
Now, trying to get the image is another issue. I am trying to use :
<?php echo esc_html( $item->the_post_thumbnail() ); ?>
But I get the error : Fatal error: Call to undefined method SimplePie_Item::the_post_thumbnail()
So, using SimplePie, is there a way to get the posts image?
MAJOR EDIT:
This way of getting the RSS feed isn't great, it is causing alot of issues throughout the site, so if anyone could show me/direct me to something where I can get the 4 latest posts from another WordPress site, that'd be awesome!
If you dont want to use WP REST API, you can give a try to Wordpress Developers API.
You will have to authorize Wordpress Jetpack plugin for this. And then enable the REST API.
As you've found, WordPress feeds have some limitations. Since you've asked for an alternative solution, I'd definitely recommend using WP REST API.
Since WP API isn't yet part of the WP Core, you'll want to do the following:
http://yoursite.com/wp-json/posts
Since you only want four posts, you can use filters:
To get this JSON into a usable state in PHP:
You can now digest this
$posts
array however you want (by looping through it). For example:More info in the WP API docs.