0

我正在尝试制作一个函数,该函数采用 rss fedd URL 并获取最近的 2 个帖子。我试图将此处的代码段重新制作为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;
}

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

4

1 回答 1

0

使用 WordPress 的内置 RSS 功能要容易得多。见https://codex.wordpress.org/Function_Reference/fetch_feed

在 php 模板中多次使用它,或者让它生成一个简码。如果需要,设置 and 的样式<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>
于 2015-05-09T22:22:33.537 回答