Skip to Main Content
Docs Navigation
DK Developer Portal v1.2.0

DK Developer Manual

Step-by-step setup guides, deep configuration details, optimization strategies, and robust headless integration guidelines.

Introduction to DK Headless API

Welcome to the official developer documentation for the **DK Headless API for WordPress**. DK Headless API works as a high-performance system-decoupling framework and middleware layer built directly into WordPress.

By serving as an intercept gateway between incoming client HTTP requests and the internal WordPress REST API Controller, DK Headless API completely eliminates the payload bloat of default WordPress JSON responses. It allows you to expose secure, pruned, whitelisted endpoints with custom URL namespaces, static Next.js cache bypass parameters, and custom CORS rules.

Request Whitelisting

Verifies origin headers against strict client hostnames before computing expensive WP queries.

JSON Payload Pruning

Filters out links, headers, metadata, authors and comments dependencies to decrease payload sizes by up to 85%.

Revalidation Sync

Provides built-in tag caches and revalidation timestamps to power highly responsive Next.js ISR architectures.

System Requirements

Before deploying the DK Headless API plugin, please verify that your hosting server environment matches the following core requirements:

DependencyRequired VersionRecommended
PHP Enginev8.0+v8.2 or v8.3
WordPress Corev6.0+v6.4 or newer
Next.js Frameworkv13.4+ (App Router)v14.0+ / v15.0+
Web ServerApache, Nginx, or LiteSpeedNginx (with FastCGI caching enabled)

PHP Extension Notice: DK Headless API requires standard PHP extensions `ext-json` and `ext-curl` active on your web server configurations to process outbound API validation requests.

Installation Guide

You can install DK Headless API on your WordPress site using either manual upload panel or terminal-based dependency management via Composer.

Method A: WordPress Admin Upload

  1. Install directly by searching for DK Headless API in your admin plugins panel, or download the zip from the official WordPress.org Directory.
  2. If using manual install, navigate to Plugins > Add New > Upload Plugin and upload the zip file.
  3. Once installed, click Activate Plugin.

Method B: Composer (Recommended for Production VCS)

If you manage WordPress dependencies via Composer (using templates like Bedrock), execute the following commands in your theme/plugins root directory:

Terminal Console
composer require digitizedkosmos/dk-headless-api
wp plugin activate dk-headless-api

Core Platform Features

Frontend Disabling (Headless Mode)

Completely disables the traditional PHP theme rendering frontend layer (reducing load and closing template vulnerability paths) while keeping /wp-admin and /wp-json fully functional.

When frontend requests are blocked, the server responds with a clean 410 Gone status containing the following JSON payload redirects search engines and developers to the true client frontend:

{
  "success": true,
  "message": "Frontend is disabled. DK Headless API for WordPress is active.",
  "frontend_url": "https://yourfrontend.com"
}

Caching & Transient Optimization

To prevent database load, DK Headless API caches API GET requests using transients natively. The system automatically flushes cached payloads whenever pages or posts are updated or created. You can configure custom Time-To-Live (TTL) cache parameters within the settings panel.

Daily Rate Limiting

Protects your REST routes against scraping and scraping request spikes by restricting IP request counts (configured to a default maximum rate allowance of 1000 daily hits per user IP).

Custom API Namespace

By default, all WordPress REST endpoints are exposed globally under the standard `/wp-json/wp/v2/` namespace path. This leaves your backend structure vulnerable to automated scanners and aggressive bots.

With DK Headless API, you can override this globally by defining a custom route prefix (e.g. `gateway-api/v1`). The plugin will intercept requests, route queries, and returns standard 404 responses on default paths.

How to configure custom namespace:

  1. Navigate to Settings > DK Headless API for WordPress inside the WordPress Admin sidebar.
  2. Locate the API Namespace Prefix input box.
  3. Replace dk/v1 with your secret slug (e.g., secure-gateway/v2).
  4. Click Save Changes.
.env.local configuration
// Next.js project path environment variable setup
// file: .env.local
NEXT_PUBLIC_WORDPRESS_API_URL="https://backend.yoursite.com/wp-json/secure-gateway/v2"

Domain CORS Setup

Security-wise, default WordPress leaves the Access-Control-Allow-Origin wildcard header set to open (*), allowing browsers on any page to fetch data from your API.

DK Headless API injects a strict CORS intercept validation. The backend will inspect the HTTP request origin header:

Whitelisted Domain

Origin matches your list (e.g. `https://myfrontend.com`). Request compiles and serves headers `Access-Control-Allow-Origin: https://myfrontend.com`.

Blocked Domain

Origin does not match whitelist. DK Headless API returns an instant 403 Forbidden response, saving CPU cycles on database executions.

To add whitelisted domains:

  1. Navigate to the DK Configuration Panel.
  2. Click on the CORS Settings tab.
  3. Enter one domain per line in the Whitelist Textarea (e.g., https://www.yourdomain.com).
  4. Enable the toggle labeled Block Non-Whitelisted Origins.

Endpoint Pruning

Standard WordPress REST responses carry an excessive amount of nested metadata link schemas (such as the standard `_links` object, `yoast_head` HTML blogs, pingback headers, etc.). DK Headless API features native field pruning parameters.

Pruning Fields Configuration

In the DK Headless API settings interface, you can select checkboxes next to fields you want deleted from output JSON payloads. Check objects such as:

_links
ping_status
yoast_head
comment_status

API Reference Overview

All routes are registered under the custom API namespace. The default namespace is /wp-json/dk/v1/. Endpoint responses are pruned, clean, and structured to optimize payload weight.

Menus Endpoints

Retrieve header, footer, or sidebar navigation menus dynamically built inside WordPress.

GET
/menus

List all available menus and their respective item trees.

{
  "success": true,
  "data": [
    {
      "id": 12,
      "name": "Header Navigation",
      "slug": "header-navigation",
      "count": 3,
      "items": [
        {
          "id": 105,
          "title": "Home",
          "url": "https://yourfrontend.com/",
          "classes": "nav-item"
        }
      ]
    }
  ]
}
GET
/menus/<id_or_slug>

Fetch a single menu directly by its numeric ID or string slug (e.g. /menus/header-navigation).

Posts & Pages Endpoints

GET
/posts?per_page=10&page=1

Lists paginated posts with Gutenberg block trees and ACF custom fields resolved natively.

GET
/posts/<id>

Fetch a single post. Output includes fields configurations, categories, titles, blocks, and ACF data:

{
  "success": true,
  "data": {
    "id": 1,
    "title": "Hello World",
    "slug": "hello-world",
    "content": "<p>Welcome to WordPress...</p>",
    "author": "Admin",
    "fields": {
      "acf_custom_hero_title": "My Custom Value"
    }
  }
}
GET
/pages

Fetch all static pages or individual page instances (/pages/<id>) in Single Post format without excerpt fields.

GET
/<post_type_slug>s

Exposes registered Custom Post Types dynamically (e.g. /portfolios, /services).

Settings Endpoint

GET
/settings

Exposes global site settings (such as Site Name, Description, and Timezone parameters) for static SEO rendering in React/Next.js frontends.

Next.js Integration

To build high-performance static pages with automatic revalidation, integrate the custom DK Headless API endpoints in your Next.js Server Components.

lib/dk-client.ts
// file: lib/dk-client.ts
export interface DKPost {
  id: number;
  title: { rendered: string };
  content: { rendered: string };
  slug: string;
}

export async function getDKPosts(): Promise<DKPost[]> {
  const endpoint = `${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/posts`;
  
  const response = await fetch(endpoint, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
    next: { 
      revalidate: 3600, // Regenerate static build cache hourly
      tags: ["posts-feed"] 
    }
  });

  if (!response.ok) {
    throw new Error("Failed to fetch posts from DK Headless API for WordPress");
  }

  return response.json();
}

JWT Gateways
Pro Feature

If you need to fetch draft posts, private WooCommerce user profiles, or process comments securely, you can lock your routes behind JWT Token Authorization.

DK Pro verifies tokens in the HTTP authorization headers using RSA256 signature keys. If the token is invalid or expired, the request is instantly thrown out without database hits.

Secure Profile Fetch Action
// Fetching authenticated user profile in Next.js Server Action
export async function getSecureProfile(jwtToken: string) {
  const res = await fetch('https://wp.yoursite.com/wp-json/secure-gateway/v2/users/me', {
    headers: {
      'Authorization': `Bearer ${jwtToken}`
    }
  });
  return res.json();
}

Upcoming Features & Roadmap

We are actively expanding the features of the DK Headless API for WordPress plugin. Below are the key upcoming features planned in our public development backlog:

Backlog #01
In Progress

Visual API Builder

A visual drag-and-drop endpoint pruning console inside the WP Admin settings to configure response attributes without code.

Backlog #02
Planned

Batch Redirect Routing

Map and execute bulk redirect rules at the edge server level directly from WordPress into Next.js routing structures.

Backlog #03
Planned

Dynamic GraphQL Gateway

An automatic translation gateway converting pruned REST endpoints into clean, executable GraphQL schema structures.

Ecosystem Comparisons

How does DK Headless API for WordPress compare against other architectural choices? Toggle the tabs below to analyze features, latency and configurations side-by-side.

DK REST vs WPGraphQL Comparison

Why pruned REST payloads outperform complex GraphQL schemas.

WPGraphQL is powerful but introduces large plugin dependency bloat, complex query compilers, and execution latency overhead. DK Headless API prunes REST responses by up to 92% with zero compilation steps, matching Next.js caching natively.

Comparison MetricDK API (REST)WPGraphQL Alternative
Average Response Latency42ms128ms
Payload size (pruned)4.2 KB18.5 KB
Authentication gatewayJWT Whitelist (Pro)Custom plugins setup
CORS control dashboardYes (Core settings)Manual code filters

Troubleshooting

Having troubles configuring DK Headless API? Below are common error states and their typical resolutions:

Issue: Getting 404 Not Found on Custom Routes

WordPress permalinks structural rules cache must be flushed to register custom routes. In WP-Admin, navigate to Settings > Permalinks and click Save Changes (this triggers a flush of rewrite rules).

Issue: CORS Origin Blocking errors on Localhost

Make sure your local dev server address (e.g. http://localhost:3000) is explicitly listed inside the CORS Whitelist text area.

Issue: Next.js revalidation triggers a 500 error

Verify that your client server clock is synchronized with the WP host engine. Discrepancies of more than 180 seconds will trigger token cache check validation exceptions.