PHPackages                             baraja-core/wordpress-post-feed - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. baraja-core/wordpress-post-feed

ActiveLibrary[API Development](/categories/api)

baraja-core/wordpress-post-feed
===============================

API service for downloading a list of new blog posts.

v2.2.2(1y ago)1206[1 PRs](https://github.com/baraja-core/wordpress-post-feed/pulls)PHPPHP ^8.0CI passing

Since Oct 29Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/baraja-core/wordpress-post-feed)[ Packagist](https://packagist.org/packages/baraja-core/wordpress-post-feed)[ Docs](https://github.com/baraja-core/wordpress-post-feed)[ RSS](/packages/baraja-core-wordpress-post-feed/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (10)Versions (19)Used By (0)

   ![BRJ logo](https://camo.githubusercontent.com/813c67e02a7ab7e4dc900316a4521c3ddf5846fe2cabba7140f3f4b78afda198/68747470733a2f2f63646e2e62726a2e6170702f696d616765732f62726a2d6c6f676f2f6c6f676f2d6461726b2e706e67)
 [BRJ organisation](https://brj.app)

---

WordPress Post Feed
===================

[](#wordpress-post-feed)

A lightweight PHP library for fetching, parsing, and caching WordPress RSS feeds with automatic image handling.

The library provides a simple API to download blog posts from any WordPress RSS feed, automatically caches the content to minimize network requests, and handles image downloading and local storage for improved performance and reliability.

✨ Key Features
--------------

[](#sparkles-key-features)

- **Automatic RSS feed parsing** - Extracts posts with title, description, link, date, author, and categories
- **Smart caching system** - Feed content is cached with configurable expiration time (default: 2 hours)
- **Image management** - Automatically downloads and stores post images locally
- **Pagination support** - Built-in `limit` and `offset` parameters for easy pagination
- **Zero-config usage** - Works out of the box without any dependencies when used standalone
- **Nette Framework integration** - Full DI container support with configurable extension
- **Security-first image handling** - Validates image types before saving to prevent malicious files

🏗️ Architecture Overview
------------------------

[](#building_construction-architecture-overview)

The library consists of four main components that work together to provide a complete feed management solution:

```
┌─────────────────────────────────────────────────────────────────────┐
│                        WordPress RSS Feed                           │
│                    (External WordPress Blog)                        │
└───────────────────────────────┬─────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────────┐
│                           Feed Service                              │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │  • Downloads RSS feed via cURL                              │   │
│  │  • Parses XML using DOMDocument                             │   │
│  │  • Extracts post data (title, description, link, date...)   │   │
│  │  • Manages cache read/write operations                      │   │
│  │  • Extracts images from post descriptions                   │   │
│  └─────────────────────────────────────────────────────────────┘   │
└───────────────────────────────┬─────────────────────────────────────┘
                                │
                ┌───────────────┴───────────────┐
                ▼                               ▼
┌───────────────────────────────┐ ┌───────────────────────────────────┐
│         Nette Cache           │ │         ImageStorage              │
│  ┌─────────────────────────┐  │ │  ┌─────────────────────────────┐  │
│  │ • FileStorage (default) │  │ │  │ • Downloads images via cURL │  │
│  │ • Configurable TTL      │  │ │  │ • Validates image types     │  │
│  │ • Auto-invalidation     │  │ │  │ • Stores to local disk      │  │
│  └─────────────────────────┘  │ │  │ • Generates URLs            │  │
└───────────────────────────────┘ │  └─────────────────────────────┘  │
                                  └───────────────────────────────────┘
                                                  │
                                                  ▼
                                  ┌───────────────────────────────────┐
                                  │           Post Entity             │
                                  │  ┌─────────────────────────────┐  │
                                  │  │ • title (string)            │  │
                                  │  │ • description (string)      │  │
                                  │  │ • link (string)             │  │
                                  │  │ • date (DateTimeImmutable)  │  │
                                  │  │ • creator (string|null)     │  │
                                  │  │ • categories (array)        │  │
                                  │  │ • mainImageUrl (string|null)│  │
                                  │  └─────────────────────────────┘  │
                                  └───────────────────────────────────┘

```

### 📦 Components

[](#package-components)

ComponentDescription`Feed`Main service responsible for downloading, parsing, and caching RSS feeds. Orchestrates the entire feed retrieval process.`Post`Data entity representing a single blog post with all its properties and image URL helpers.`ImageStorage`Service for downloading, validating, and storing images locally. Provides URL generation for stored images.`WordpressPostFeedExtension`Nette DI extension for seamless framework integration with full configuration support.📦 Installation
--------------

[](#package-installation)

It's best to use [Composer](https://getcomposer.org) for installation, and you can also find the package on [Packagist](https://packagist.org/packages/baraja-core/wordpress-post-feed) and [GitHub](https://github.com/baraja-core/wordpress-post-feed).

To install, simply use the command:

```
$ composer require baraja-core/wordpress-post-feed
```

You can use the package manually by creating an instance of the internal classes, or register a DIC extension to link the services directly to the Nette Framework.

### Requirements

[](#requirements)

- PHP 8.0 or higher
- ext-curl extension
- Nette Caching component (installed automatically)

⚙️ Configuration
----------------

[](#gear-configuration)

### Standalone Usage

[](#standalone-usage)

The library works out of the box without any configuration:

```
$feed = new \Baraja\WordPressPostFeed\Feed;
```

By default, the `Feed` service will:

- Create a temporary directory for caching in the system temp folder
- Set cache expiration to 2 hours
- Create an `ImageStorage` instance with default settings

### Nette Framework Integration

[](#nette-framework-integration)

If you are installing the package into the Nette Framework, register the extension in your configuration:

```
extensions:
    wordpressPostFeed: Baraja\WordPressPostFeed\WordpressPostFeedExtension
```

### Advanced Configuration

[](#advanced-configuration)

The extension supports the following configuration options:

```
wordpressPostFeed:
    # Cache expiration time (supports human-readable format)
    expirationTime: '2 hours'

    # Absolute path for image storage
    imageStoragePath: '%wwwDir%/assets/blog-images'

    # Relative path used in URLs (required when imageStoragePath is set)
    imageRelativeStoragePath: 'assets/blog-images'
```

OptionTypeDefaultDescription`expirationTime`string`'2 hours'`Cache expiration time in human-readable format`imageStoragePath`string`null`Absolute filesystem path for storing images`imageRelativeStoragePath`string`'wordpress-post-feed'`Relative URL path for accessing stored images🚀 Basic Usage
-------------

[](#rocket-basic-usage)

### Loading Posts from a Feed

[](#loading-posts-from-a-feed)

```
$feed = new \Baraja\WordPressPostFeed\Feed;

$posts = $feed->load('https://blog.example.com/feed/');

foreach ($posts as $post) {
    echo $post->getTitle();
    echo $post->getDescription();
    echo $post->getLink();
    echo $post->getDate()->format('Y-m-d');
    echo $post->getCreator();
    echo json_encode($post->getCategories());
    echo $post->getMainImageUrl();
}
```

The feed will be downloaded automatically, then cached and further requests will be handled instantly straight from the cache.

### Pagination with Limit and Offset

[](#pagination-with-limit-and-offset)

If you only need to retrieve some posts from the feed, use the `limit` and `offset` arguments:

```
$posts = $feed->load(
    url: 'https://blog.example.com/feed/',
    limit: 3,
    offset: 1,
);
```

ParameterTypeDefaultDescription`url`stringrequiredThe URL of the WordPress RSS feed`limit`int|null`null`Maximum number of posts to return (null = all)`offset`int`0`Number of posts to skip from the beginning### Post Entity Methods

[](#post-entity-methods)

The `Post` entity provides the following methods:

MethodReturn TypeDescription`getTitle()``string`Returns the post title (HTML tags stripped)`getDescription()``string`Returns the post description/excerpt`getLink()``string`Returns the permalink to the original post`getDate()``DateTimeImmutable`Returns the publication date`getCreator()``string|null`Returns the author name`getCategories()``array`Returns an array of category names`getMainImageUrl()``string|null`Returns the original external image URL`getAbsoluteInternalUrl()``string|null`Returns the absolute URL to locally stored image`getRelativeInternalUrl()``string|null`Returns the relative URL to locally stored image💾 Caching System
----------------

[](#floppy_disk-caching-system)

### How Caching Works

[](#how-caching-works)

Posts are automatically cached for the set period (default 2 hours). The caching system operates on two levels:

1. **Raw feed caching** - The downloaded XML feed is cached to avoid repeated HTTP requests
2. **Parsed post caching** - The parsed `Post` objects are cached separately for each limit/offset combination

When the cache expires, the next request will:

1. Download the fresh feed
2. Parse all posts
3. Store images locally
4. Update the cache

### Cache Management

[](#cache-management)

#### Manual Cache Update

[](#manual-cache-update)

If you want to refresh the cache before expiration (e.g., via cron job):

```
$feed = new \Baraja\WordPressPostFeed\Feed;
$feed->updateCache('https://blog.example.com/feed/');
```

This is useful for ensuring all requests are served from cache instantly, even after expiration.

#### Clear All Cache

[](#clear-all-cache)

To completely clear the feed cache:

```
$feed = new \Baraja\WordPressPostFeed\Feed;
$feed->clearCache();
```

### Recommended Cron Setup

[](#recommended-cron-setup)

For production environments, it's recommended to set up a cron job that refreshes the cache periodically:

```
// cron.php - Run every hour
$feed = new \Baraja\WordPressPostFeed\Feed;

$feedUrls = [
    'https://blog.example.com/feed/',
    'https://another-blog.com/feed/',
];

foreach ($feedUrls as $url) {
    $feed->updateCache($url);
}
```

This ensures that user requests are always served from cache and never have to wait for feed downloads.

🖼️ Image Manipulation
---------------------

[](#framed_picture-image-manipulation)

When downloading posts from the feed, images are automatically downloaded and copied to disk. The image storage is provided by the `\Baraja\WordPressPostFeed\ImageStorage` service, which is automatically registered by the library.

### Default Storage Location

[](#default-storage-location)

The default directory for storing images is `wordpress-post-feed` relative to your `index.php` (web root).

### ImageStorage Service Methods

[](#imagestorage-service-methods)

The service provides the following methods:

MethodDescription`save(string $url): void`Downloads the image from the URL and saves it to disk`getInternalPath(string $url): string`Returns the absolute filesystem path for the image`getAbsoluteInternalUrl(string $url): string`Returns the absolute URL to retrieve the image`getRelativeInternalUrl(string $url): string`Returns the relative URL to retrieve the image### Working with Images from Posts

[](#working-with-images-from-posts)

Working with images is also available directly from the `Post` entity:

```
foreach ($posts as $post) {
    // Original external URL (from WordPress)
    $externalUrl = $post->getMainImageUrl();

    // Local absolute URL (your domain)
    $absoluteUrl = $post->getAbsoluteInternalUrl();

    // Local relative URL (for use in templates)
    $relativeUrl = $post->getRelativeInternalUrl();
}
```

### Supported Image Formats

[](#supported-image-formats)

The library validates downloaded images and supports the following formats:

FormatConstantJPEG`ImageStorage::JPEG`PNG`ImageStorage::PNG`GIF`ImageStorage::GIF`WebP`ImageStorage::WEBP`BMP`ImageStorage::BMP`If a downloaded file is not a valid image of these types, a `RuntimeException` is thrown to prevent potential security issues.

### Image Naming Strategy

[](#image-naming-strategy)

Images are stored with a deterministic naming scheme to prevent collisions and ensure readability:

1. A 7-character MD5 hash prefix is generated from the URL
2. The original filename is sanitized (webalized) and truncated to 64 characters
3. Files are organized into subdirectories based on WordPress date structure (YYYY-MM) or URL hash

Example: `https://blog.example.com/wp-content/uploads/2024/03/my-image.jpg` becomes:

```
wordpress-post-feed/2024-03/a1b2c3d-my-image.jpg

```

🛠️ Advanced Usage
-----------------

[](#hammer_and_wrench-advanced-usage)

### Custom Cache Storage

[](#custom-cache-storage)

You can provide your own cache storage implementation:

```
use Nette\Caching\Storages\MemcachedStorage;

$memcached = new Memcached;
$memcached->addServer('localhost', 11211);

$storage = new MemcachedStorage($memcached);
$feed = new \Baraja\WordPressPostFeed\Feed(storage: $storage);
```

### Custom Image Storage Location

[](#custom-image-storage-location)

```
$imageStorage = new \Baraja\WordPressPostFeed\ImageStorage(
    storagePath: '/var/www/html/assets/blog-images',
    relativeStoragePath: 'assets/blog-images',
);

$feed = new \Baraja\WordPressPostFeed\Feed(imageStorage: $imageStorage);
```

### Custom Expiration Time

[](#custom-expiration-time)

```
$feed = new \Baraja\WordPressPostFeed\Feed(
    expirationTime: '30 minutes',
);
```

Supported time formats include: `'1 hour'`, `'30 minutes'`, `'2 days'`, etc.

### Dependency Injection in Nette

[](#dependency-injection-in-nette)

When using the Nette Framework, you can inject the services directly:

```
final class BlogPresenter extends Nette\Application\UI\Presenter
{
    public function __construct(
        private \Baraja\WordPressPostFeed\Feed $feed,
    ) {
    }

    public function renderDefault(): void
    {
        $this->template->posts = $this->feed->load(
            url: 'https://blog.example.com/feed/',
            limit: 5,
        );
    }
}
```

⚠️ Error Handling
-----------------

[](#warning-error-handling)

The library handles errors gracefully:

- **Empty feed response** - Throws `RuntimeException` with descriptive message
- **Invalid image format** - Throws `RuntimeException` to prevent security issues
- **Broken image URLs** - Triggers a warning but continues processing
- **Invalid feed URLs** - Triggers a warning but continues processing
- **Missing absolute URL in CLI** - Throws `LogicException` with guidance

Example of handling errors:

```
try {
    $posts = $feed->load('https://blog.example.com/feed/');
} catch (\RuntimeException $e) {
    // Handle feed loading errors
    error_log('Feed error: ' . $e->getMessage());
}
```

👤 Author
--------

[](#bust_in_silhouette-author)

**Jan Barasek**

- Website:
- GitHub: [@janbarasek](https://github.com/janbarasek)

📄 License
---------

[](#page_facing_up-license)

`baraja-core/wordpress-post-feed` is licensed under the MIT license. See the [LICENSE](https://github.com/baraja-core/wordpress-post-feed/blob/master/LICENSE) file for more details.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance57

Moderate activity, may be stable

Popularity13

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 98.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~101 days

Recently: every ~242 days

Total

14

Last Release

700d ago

Major Versions

v1.1.0 → v2.0.02021-02-09

PHP version history (3 changes)v1.0.0PHP &gt;=7.4.0

v1.1.0PHP ^7.4 || ^8.0

v2.0.0PHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3382204?v=4)[baraja](/maintainers/baraja)[@baraja](https://github.com/baraja)

---

Top Contributors

[![janbarasek](https://avatars.githubusercontent.com/u/4738758?v=4)](https://github.com/janbarasek "janbarasek (62 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (1 commits)")

---

Tags

apiarticlesfeedphprsswordpresswordpress-rsswp

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/baraja-core-wordpress-post-feed/health.svg)

```
[![Health](https://phpackages.com/badges/baraja-core-wordpress-post-feed/health.svg)](https://phpackages.com/packages/baraja-core-wordpress-post-feed)
```

###  Alternatives

[apigen/apigen

PHP source code API generator.

2.2k627.9k225](/packages/apigen-apigen)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
