我正在尝试使用以下来自http://codex.wordpress.org/Function_Reference/fetch_feed#Usage的代码从我的个人网站获取 2 个最新帖子
<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; ?>
Run Code Online (Sandbox Code Playgroud)
有了这段代码,我就可以得到帖子的网址、标题和发帖日期,太棒了!
现在,尝试获取图像是另一个问题。我正在尝试使用:
<?php echo esc_html( $item->the_post_thumbnail() ); ?>
Run Code Online (Sandbox Code Playgroud)
但我收到错误:致命错误:调用未定义的方法 SimplePie_Item::the_post_thumbnail()
那么,使用 SimplePie,有没有办法获取帖子图片?
主要编辑:
这种获取 RSS 提要的方式并不好,它在整个网站上引起了很多问题,所以如果有人可以向我展示/引导我到可以从另一个 WordPress 站点获取 4 个最新帖子的地方,那就是惊人的!
正如您所发现的,WordPress 提要有一些限制。由于您要求提供替代解决方案,因此我绝对建议您使用WP REST API。
由于 WP API 还不是 WP 核心的一部分,您需要执行以下操作:
http://yoursite.com/wp-json/posts由于您只需要四个帖子,您可以使用过滤器:
http://yoursite.com/wp-json/posts?filter[posts_per_page]=4
Run Code Online (Sandbox Code Playgroud)
要在 PHP 中将此 JSON 变为可用状态:
// Get the JSON
$json = file_get_contents('http://yoursite.com/wp-json/posts?filter[posts_per_page]=4');
// Convert the JSON to an array of posts
$posts = json_decode($json);
Run Code Online (Sandbox Code Playgroud)
您现在可以根据需要消化这个$posts数组(通过循环遍历它)。例如:
foreach ($posts as $p) {
echo '<p>Title: ' . $p->title . '</p>';
echo '<p>Date: ' . date('F jS', strtotime($p->date)) . '</p>';
// Output the featured image (if there is one)
echo $p->featured_image ? '<img src="' . $p->featured_image->guid . '">' : '';
}
Run Code Online (Sandbox Code Playgroud)
WP API 文档中的更多信息。
| 归档时间: |
|
| 查看次数: |
17688 次 |
| 最近记录: |