Function and usage of fetch_rss() in wordpress


Answers ( 1 )


    The fetch_rss() function in WordPress is a tool used for retrieving RSS feeds from specified URLs and converting them into a MagpieRSS object. This function is particularly useful for integrating external RSS feed content into a WordPress site. Here's a detailed explanation and a sample usage:

    Function Signature:

    fetch_rss( string $url ): MagpieRSS|false

    Function Details:

    1. Purpose:

      • The fetch_rss() function is designed to build a MagpieRSS object based on an RSS feed retrieved from a given URL. This allows WordPress to parse and utilize the content of external RSS feeds.
    2. Parameters:

      • $url (string, required): This is the URL of the RSS feed you want to retrieve. The URL must point to a valid RSS feed.
    3. Return Value:

      • The function returns a MagpieRSS object on successful retrieval and parsing of the RSS feed.
      • It returns false if the retrieval or parsing fails. This failure can occur due to reasons like an invalid URL, a non-responsive server, or an invalid RSS format.

    Sample Usage:

    // Include the RSS fetching functionality (if not already included)
    require_once(ABSPATH . WPINC . '/rss.php');
    // URL of the RSS feed
    $feed_url = '';
    // Fetch the RSS feed
    $rss = fetch_rss($feed_url);
    // Check if the RSS fetch was successful
    if ($rss) {
        // Iterate through each item in the feed
        foreach ($rss->items as $item) {
            // Title of the feed item
            $title = $item['title'];
            // Description of the feed item
            $description = $item['description'];
            // Output the title and description
            echo "<h2>$title</h2>";
            echo "<p>$description</p>";
    } else {
        // Output an error message if the fetch failed
        echo "Failed to fetch RSS feed from $feed_url";

    In this sample usage, the fetch_rss() function is used to retrieve an RSS feed from a specified URL. The script first checks if the feed has been successfully fetched. If so, it iterates through the items in the feed, extracting and displaying the title and description of each item. If the feed cannot be fetched, it outputs an error message.

Leave an answer