# Enhanced WP REST API Plugin
> Open-source WordPress plugin extending REST API for headless CMS architectures. Features GA4 analytics integration, Polylang translation data for proper hreflang SEO implementation, relative URLs, and headless mode with 301 redirects.
- URL: https://spoko.space/enhanced-wp-rest-api/
- Published: 2025-08-20
- Tags: wordpress, rest-api, headless-cms, php, open-source, polylang, ga4, astro
---## Enhanced WordPress REST API

I developed an open-source WordPress plugin that extends the REST API specifically for headless CMS architectures. The plugin enables WordPress to function as a robust backend API while modern frontend frameworks like Astro, Next.js, or Nuxt handle the presentation layer.

## The Problem

WordPress's default REST API provides basic functionality but lacks essential features for production headless implementations:
- Incomplete data structures requiring multiple API calls
- Absolute URLs causing issues across environments (dev, staging, production)
- No built-in analytics integration for popular posts
- Limited multilingual support
- Missing headless mode redirects
- No custom taxonomy ordering

This plugin solves these challenges with a comprehensive set of enhancements designed from real-world headless WordPress projects.

## Key Features

### Enhanced Data Structure

The plugin enriches standard REST API responses with additional fields that frontend applications need:

**Extended Author Data** - Complete author information including ID, name, nicename, avatar URL, description, and relative author page links in a single response. No need for separate `/users` endpoint calls.

**Multiple Image Sizes** - The `featured_image_urls` field provides all registered WordPress image sizes (thumbnail, medium, large, full), eliminating the need for additional API calls to fetch different dimensions for responsive images.

**Reading Time Estimates** - Automatic calculation of estimated reading duration based on content length (e.g., "5 min read"), useful for blog layouts and improving user experience.

**Rich Taxonomy Information** - Expanded category and tag data with descriptions, post counts, parent category IDs, and relative URLs in the main post response.

### Environment-Agnostic URLs

All URLs in API responses are converted to relative paths (e.g., `/blog/post-name/` instead of `https://example.com/blog/post-name/`). This applies to:
- Post permalinks
- Author page URLs
- Category and tag archive URLs
- Featured image URLs
- Translation URLs (when Polylang is active)

**Benefits:**
- Consistent behavior across development, staging, and production environments
- No need for environment-specific configuration or search-replace operations
- Easier deployment workflows and testing
- Frontend can construct full URLs with its own domain

### Polylang Integration

Seamless multilingual support when [Polylang](https://polylang.pro/) plugin is active:

**Translation Data** - The `translations_data` field exposes all available translations for posts, categories, and tags with complete information:
- Post translations include ID, title, slug, excerpt, status, featured image ID, and relative link
- Category/tag translations include ID, name, slug, and relative link
- Perfect for building language switchers in headless frontends
- **Critical for SEO** - enables proper `hreflang` tag implementation in Astro and other frontend frameworks, which was previously impossible to achieve efficiently without this data in the REST API response

**Available Languages** - Lists all site languages in the `available_languages` field

**Language Filtering** - Automatic language-aware API queries respect current language context

**Why this matters for SEO:** Without the `translations_data` field, implementing proper hreflang tags in a headless architecture would require additional API calls for each translation, making it impractical for static site generation. This plugin solves this problem by providing all translation URLs in a single response, enabling search engines to correctly identify language variants and serve the right content to users.

### GA4 Analytics Integration

Fetch popular posts based on real Google Analytics 4 pageview data instead of simple view counters:

**Features:**
- Posts ranked by actual pageviews from GA4
- Configurable time periods: 7, 14, 30, or 90 days
- Language filtering for multilingual sites (Polylang integration)
- Smart caching with configurable duration (1-24 hours)
- JWT-based service account authentication
- No Google SDK required - lightweight implementation using WordPress HTTP API

**API Endpoint:**
```
/wp-json/wp/v2/posts/popular?limit=6&period=7d&lang=pl
```

**Response includes:**
- Post data with all enhanced fields
- Pageview counts for each post
- Cache status and timestamp
- Total results and period information

This enables dynamic "trending posts" sections based on actual user behavior, perfect for increasing engagement and content discovery.

### Headless Mode

Optional complete frontend redirect functionality for true headless WordPress:

**How it works:**
- 301 redirects send all frontend visitors to your headless application
- Original URL paths are preserved for SEO (e.g., `/blog/post-slug` → `https://frontend.com/blog/post-slug`)
- Admin panel remains accessible for authorized users (`edit_posts` capability)
- REST API, GraphQL, WP-CLI, and CRON continue functioning normally

**Benefits:**
- Maintain WordPress as a pure backend/CMS
- Prevent duplicate content issues
- Proper SEO-friendly redirects
- No need for separate headless mode plugins

### Custom Taxonomy Ordering

Support for ordered categories and tags via `term_order` parameter:

```
/wp-json/wp/v2/categories?orderby=term_order
/wp-json/wp/v2/tags?orderby=term_order
```

Respects manual taxonomy ordering from plugins, ensuring consistent navigation across WordPress admin and headless frontend. Categories default to ascending order.

### Comments API Enhancement

Optional REST API configuration for anonymous commenting:
- Allow unauthenticated comment submission via REST API
- Configurable moderator email notifications for new comments
- Perfect for Jamstack contact forms and headless comment systems
- All configured through WordPress admin panel

## Code Example

```javascript
// Fetch posts with all enhanced data
fetch('/wp-json/wp/v2/posts')
  .then(res => res.json())
  .then(posts => {
    const post = posts[0];

    // Relative URLs ready for frontend
    console.log(post.relative_link);        // "/blog/post-title"
    console.log(post.author_data.url);      // "/author/john-doe"

    // Complete author data in one response
    console.log(post.author_data);
    // {
    //   id: 1,
    //   name: "John Doe",
    //   nicename: "john-doe",
    //   avatar: "/path/to/avatar.jpg",
    //   description: "Author bio...",
    //   url: "/author/john-doe"
    // }

    // All image sizes available
    console.log(post.featured_image_urls);
    // {
    //   thumbnail: "/uploads/image-150x150.jpg",
    //   medium: "/uploads/image-300x200.jpg",
    //   large: "/uploads/image-1024x768.jpg",
    //   full: "/uploads/image.jpg"
    // }

    // Reading time estimate
    console.log(post.read_time); // "5 min read"

    // Multilingual data (when Polylang active)
    console.log(post.translations_data);
    console.log(post.available_languages); // ["en", "pl"]
  });
```

## Real-World Usage

This plugin was developed for and powers the [polo.blue](https://polo.blue) blog - a multilingual automotive enthusiast blog built with Astro frontend and WordPress headless backend.

**polo.blue Implementation:**
- **WordPress Backend** - Content management with Polylang for Polish/English translations
- **Astro Frontend** - Static site generation consuming enhanced REST API
- **GA4 Integration** - Popular posts sections based on real pageview data
- **Relative URLs** - Seamless deployment across multiple environments
- **Headless Mode** - Complete frontend separation with 301 redirects

The plugin is also suitable for other headless WordPress implementations:
- Multilingual blogs with modern frontend frameworks
- Content sites with GA4-based trending sections
- Marketing websites with WordPress backend and Next.js/Nuxt presentation
- E-commerce content management with custom taxonomies

The plugin is actively maintained and battle-tested in production environments.

## Used Technologies

The plugin is open-source (GPL v2 or later) and available on GitHub for community contributions. All features are optional and individually configurable via the WordPress admin panel.