在一页中从其他博客获取多个 RSS 提要

Fetch several rss feeds from other blogs in one page

我正在尝试创建一个函数,该函数采用 rss fedd URL 并获取最新的 2 个帖子。我已尝试将 here 中的代码片段重新制作为 funtions.php 中的完整功能,如下所示。我不想为此使用插件,因为我看过的插件几乎不可能用我自己的 html...

function fetch_feed_from_blogg($path) {
$rss = fetch_feed($path);

if (!is_wp_error( $rss ) ) : 

    $maxitems = $rss->get_item_quantity(2); 
    $rss_items = $rss->get_items(0, $maxitems); 
endif;

function get_first_image_url($html)
    {
      if (preg_match('/<img.+?src="(.+?)"/', $html, $matches)) {
      return $matches[1];
      }
    }

function shorten($string, $length) 
{
    $suffix = '&hellip;';

    $short_desc = trim(str_replace(array("/r", "/n", "/t"), ' ', strip_tags($string)));
        $desc = trim(substr($short_desc, 0, $length));
        $lastchar = substr($desc, -1, 1);
          if ($lastchar == '.' || $lastchar == '!' || $lastchar == '?') $suffix='';
              $desc .= $suffix;
        return $desc;
}

    if ($maxitems == 0) echo '<li>No items.</li>';
    else 
    foreach ( $rss_items as $item ) :

$html = '<ul class="rss-items" id="wow-feed"> <li class="item"> <span class="rss-image"><img src="' .get_first_image_url($item->get_content()). '"/></span>
        <span class="data"><h5><a href="' . esc_url( $item->get_permalink() ) . '" title="' . esc_html( $item->get_title() ) . '"' . esc_html( $item->get_title() ) . '</a></h5></li></ul>';

   return $html;
}

我也在努力让它可以在一个页面上多次使用。

WordPress内置的RSS功能更易用。参见 https://codex.wordpress.org/Function_Reference/fetch_feed

在 php 模板中任意多次使用它,或让它生成简码。设置 <ul><li> 的样式,并根据需要添加包含 <div> 的样式。

示例:

<?php // Get RSS Feed(s)
include_once( ABSPATH . WPINC . '/feed.php' );

// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed( 'http://example.com/rss/feed/goes/here' );

$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( 5 ); 

    // 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 ) : ?>
            <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() ); ?>
                </a>
            </li>
        <?php endforeach; ?>
    <?php endif; ?>
</ul>