2015-05-09 363 views
0

我正在試圖製作一個函數,它需要一個rss fedd URL並獲取最近的2個帖子。我試圖將here中的代碼片段複製到funtions.php中的全部函數中,如下所示。我不想使用插件這個,因爲我看着已經接近不可能的風格與我自己的HTML插件...在一個頁面中從其他博客獲取幾個rss提要

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; 
} 

我也試圖讓這個它可以在單個頁面上多次使用。

回答

0

更容易使用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> 
+0

由於它的工作原理! :) – HannesH

相關問題