Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
Wordpress

WordPress: Use REST API to Build Headless WordPress Applications

- 30.03.26 - ErcanOPAK

🚀 WordPress as Content API

WordPress theme limiting you? Build React/Vue frontend, use WordPress as content source. REST API turns WordPress into headless CMS.

Built-in Endpoints

# All built-in, no setup needed!

# Get all posts
GET https://yoursite.com/wp-json/wp/v2/posts

# Get single post
GET https://yoursite.com/wp-json/wp/v2/posts/123

# Get pages
GET https://yoursite.com/wp-json/wp/v2/pages

# Get categories
GET https://yoursite.com/wp-json/wp/v2/categories

# Get tags
GET https://yoursite.com/wp-json/wp/v2/tags

# Get media
GET https://yoursite.com/wp-json/wp/v2/media

# Get users
GET https://yoursite.com/wp-json/wp/v2/users

🎯 Fetch Posts with JavaScript

// Fetch latest posts
async function getPosts() {
  const response = await fetch('https://yoursite.com/wp-json/wp/v2/posts?per_page=10');
  const posts = await response.json();
  
  posts.forEach(post => {
    console.log(post.title.rendered);
    console.log(post.excerpt.rendered);
    console.log(post.link);
  });
}

// With filters
const response = await fetch(
  'https://yoursite.com/wp-json/wp/v2/posts?' + 
  'categories=5&' +
  'per_page=5&' +
  'orderby=date&' +
  'order=desc'
);

// Search posts
const searchResponse = await fetch(
  'https://yoursite.com/wp-json/wp/v2/posts?search=react'
);

React Example: Blog Feed

import { useEffect, useState } from 'react';

function BlogFeed() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchPosts() {
      try {
        const response = await fetch(
          'https://yoursite.com/wp-json/wp/v2/posts?_embed'
        );
        const data = await response.json();
        setPosts(data);
      } catch (error) {
        console.error('Error fetching posts:', error);
      } finally {
        setLoading(false);
      }
    }

    fetchPosts();
  }, []);

  if (loading) return 
Loading...
; return (
{posts.map(post => (

{post.title.rendered}

{/* Featured image via _embed */} {post._embedded?.['wp:featuredmedia']?.[0] && ( {post.title.rendered} )}
Read More
))}
); }

Custom Endpoints

// functions.php - Create custom endpoint

add_action('rest_api_init', function() {
  register_rest_route('myplugin/v1', '/popular-posts', array(
    'methods' => 'GET',
    'callback' => 'get_popular_posts',
    'permission_callback' => '__return_true'
  ));
});

function get_popular_posts($request) {
  $args = array(
    'post_type' => 'post',
    'posts_per_page' => 10,
    'meta_key' => 'views',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
  );
  
  $posts = get_posts($args);
  
  $data = array();
  foreach ($posts as $post) {
    $data[] = array(
      'id' => $post->ID,
      'title' => $post->post_title,
      'views' => get_post_meta($post->ID, 'views', true),
      'link' => get_permalink($post->ID)
    );
  }
  
  return rest_ensure_response($data);
}

// Access: GET /wp-json/myplugin/v1/popular-posts

Authentication

🔐 JWT Authentication

// Install JWT plugin: jwt-authentication-for-wp-rest-api

// Login to get token
const loginResponse = await fetch('https://yoursite.com/wp-json/jwt-auth/v1/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    username: 'admin',
    password: 'password123'
  })
});

const { token } = await loginResponse.json();

// Use token for authenticated requests
const createPost = await fetch('https://yoursite.com/wp-json/wp/v2/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    title: 'New Post via API',
    content: 'Post content here',
    status: 'publish'
  })
});

✅ Use Cases

  • Next.js blog: WordPress backend, React frontend
  • Mobile apps: iOS/Android apps consuming WordPress content
  • Multi-platform: Same content on web, mobile, Apple TV
  • Microservices: WordPress as content service in architecture
  • Static site generators: Gatsby, Hugo pulling from WordPress

💡 Performance Tips

  • Use _embed: Get featured images, author in one request
  • Limit fields: ?_fields=id,title,excerpt for faster responses
  • Enable caching: Use Redis/Varnish for API responses
  • Pagination: Don’t fetch all posts at once
  • CDN: Cache JSON responses on CDN edge

🎯 Query Parameters Cheat Sheet

Parameter Example
per_page ?per_page=10
page ?page=2
search ?search=wordpress
categories ?categories=5,8
orderby ?orderby=date
_embed ?_embed

“Migrated blog to Next.js frontend with WordPress REST API backend. SEO improved (server-side rendering), load time halved, infinite design freedom. WordPress admin for content, React for UI. Best of both worlds.”

— Full-Stack Developer

Related posts:

WordPress: Use WP_Query Instead of query_posts for Custom Loops

Disable Heartbeat API Selectively (Not Globally)

WordPress Login Works Locally, Fails on Hosting

Post Views: 3

Post navigation

WordPress: Use WP-CLI for Command-Line Site Management
Kubernetes: Use HPA to Auto-Scale Pods Based on CPU/Memory

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (858)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (751)
  • Add Constraint to SQL Table to ensure email contains @ (578)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (564)
  • Average of all values in a column that are not zero in SQL (531)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (489)
  • Find numbers with more than two decimal places in SQL (447)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (858)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (751)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com