Skip to content

Headless WordPress the core code snippets and setup steps to launch

By Published 8 min read

On this page (8 sections)
  1. Key takeaways
  2. What is headless WordPress
  3. Basic code examples for headless WordPress setup
  4. How to connect WordPress backend with frontend via API
  5. Differences from traditional WordPress code
  6. Common pitfalls and how to test your headless site
  7. Headless codes for WordPress the core code snippets and setup steps
  8. Questions people still ask

In short: Headless WordPress is a setup where WordPress handles backend content management only, exposing data via REST API to a separate frontend. Key code snippets include enabling REST API endpoints and fetching data via JavaScript or other frameworks to display content.

Part of our guide on tools for broken affiliate links

At a glance
REST API versionv2 (default)
API endpoint format/wp-json/wp/v2/
Common API response time200-400 ms
Typical use casecontent decoupling
Most used frontendReact / Next.js

Key takeaways

  • Headless WordPress separates backend content from frontend display.
  • Use REST API to connect WordPress backend with any frontend.
  • Core code snippets enable REST API access and data fetching.
  • Test your API endpoints and frontend integration early to catch errors.
  • Common pitfalls include CORS issues and missing API permissions.

What is headless WordPress

Headless WordPress means using WordPress purely as a backend content management system without its traditional frontend theme rendering.

Instead of PHP-generated pages, a separate frontend app fetches content via WordPress's REST API and displays it independently.

This approach allows flexibility in frontend technology, such as React or Vue.js, and can improve performance and design freedom.

Another aspect of headless WordPress is the ability to decouple content authors from frontend developers, which streamlines workflows in teams with specialized roles. For example, content editors continue managing posts and pages through the familiar WordPress admin interface, while frontend engineers build user interfaces with modern JavaScript frameworks that consume the API data. This separation can accelerate development and enable more complex, interactive user experiences. For the detail, see our notes on cloudflare workers operation.

Performance improvements are often cited benefits of headless setups. By offloading frontend rendering to a static site generator or a single-page application, you reduce server-side processing overhead. A typical React-based headless site can deliver initial page loads in under 1 second on a standard broadband connection, compared to 2–3 seconds for traditional PHP-rendered WordPress pages with heavy themes and plugins. This speed boost enhances user engagement and SEO rankings.

Basic code examples for headless WordPress setup

developer viewing WordPress backend and code editor
developer viewing WordPress backend and code editor

To start headless WordPress, ensure the REST API is enabled (it is by default in modern WordPress).

A simple snippet to fetch posts using JavaScript fetch could look like this: fetch('/wp-json/wp/v2/posts').then(res => res.json()).then(data => console.log(data)); Before you commit to anything, it is worth looking at headless WordPress explanation.

You can also create custom REST API endpoints by adding PHP code in your theme’s functions.php or a plugin.

For example, to add a custom field to the API response, use register_rest_field in a PHP snippet.

When extending your headless WordPress setup, you might need to implement pagination in your API requests. For instance, appending ?per_page=10&page=2 to /wp-json/wp/v2/posts fetches the second batch of 10 posts. This control allows your frontend to implement infinite scroll or paged archives efficiently. It helps to understand wordpress alternatives compared before going further.

A practical check for your REST API endpoint is to open the URL directly in a browser or a tool like Postman and verify the JSON structure matches what your frontend expects. If the data is incomplete or missing fields, revisit your PHP code to ensure proper registration and callbacks for custom fields.

  1. Ensure WordPress version is 4.7+ for built-in REST API.
  2. Use fetch or axios in your frontend to call wp-json endpoints.
  3. Add custom REST fields in PHP using register_rest_field.
  4. Test the JSON response in a browser or API client.

How to connect WordPress backend with frontend via API

The key connection is the WordPress REST API endpoint, usually at /wp-json/wp/v2/ for core content types like posts and pages.

Your frontend app (React, Vue, Angular, or plain JavaScript) sends HTTP GET requests to these endpoints to retrieve JSON data. If that sounds like your situation, read up on understanding update timing next.

Handle authentication if you need users to log in or access private content, commonly using OAuth, JWT, or cookie authentication.

Configure CORS headers on your WordPress server to allow your frontend domain to request data.

In scenarios where your frontend and WordPress backend are hosted on different domains, cross-origin resource sharing (CORS) becomes a critical configuration. Without appropriate CORS headers on the WordPress server, browsers will block requests due to the Same-Origin Policy. A typical header to add is Access-Control-Allow-Origin: https://yourfrontenddomain.com to explicitly allow your frontend to consume the API. There is more on helium 10 vs jungle scout time savings in a separate guide.

For authenticated requests, WordPress REST API supports cookie authentication if both frontend and backend share the same domain or subdomain. However, for fully decoupled apps, token-based methods like JWT are preferred. Implementing JWT requires installing plugins that generate and verify tokens and adding authorization headers to API calls.

  • REST API URLs – Use /wp-json/wp/v2/posts, /pages, /categories, etc.
  • Authentication – Needed for private endpoints; use plugins or custom tokens.
  • CORS settings – Adjust .htaccess or server config to permit frontend requests.
  • Data handling – Parse and render JSON in frontend components.

Differences from traditional WordPress code

screen showing JavaScript code fetching WordPress API
screen showing JavaScript code fetching WordPress API

Traditional WordPress themes use PHP templates to generate HTML on the server and send fully formed pages to the browser.

Headless WordPress returns raw JSON data via REST API endpoints, with no direct page rendering.

You lose native WordPress theme hooks and filters on the frontend, so SEO and page transitions require new approaches.

Frontend frameworks handle everything from routing to rendering, unlike WordPress’s PHP template system.

Comparing traditional and headless WordPress approaches
FeatureTraditional WordPressHeadless WordPress
Page renderingServer-side PHP templatesClient-side JS frameworks
Content deliveryHTML pagesJSON via REST API
Theme systemWordPress PHP themesSeparate frontend app
SEO handlingBuilt-in with templatesNeeds frontend SEO setup
What works
  • More frontend flexibility
  • Use modern JS frameworks
  • Better separation of concerns
What to watch
  • More setup complexity
  • Requires API knowledge
  • SEO requires extra work

Common pitfalls and how to test your headless site

Common issues include CORS errors blocking API calls, missing or incorrect authentication, and incomplete data responses.

Testing API endpoints independently with tools like Postman or a browser helps verify data availability and format.

Frontend debugging tools like browser devtools can identify JavaScript fetch errors or network issues.

Ensure your WordPress user roles and permissions allow API access to the data needed.

Another common pitfall is neglecting to handle API rate limits or timeouts, especially when fetching large datasets or using third-party integrations. If your frontend app requests too many API calls in a short period, the server might throttle responses or return errors. To prevent this, implement caching strategies or batch requests when possible.

Testing should also include verifying that custom REST fields return valid data across different post types and that authentication tokens expire and refresh correctly. Tools like curl can be used in command-line to simulate API calls with headers, aiding in debugging server-side issues.

  • Check CORS headers to allow your frontend domain.
  • Verify REST API endpoints return expected data.
  • Use authentication plugins for secure private data.
  • Test frontend with mock API data before live connection.

Headless codes for WordPress the core code snippets and setup steps

frontend code showing API fetch and data rendering
frontend code showing API fetch and data rendering

Here’s a basic PHP snippet to add a custom REST API field in WordPress: add_action('rest_api_init', function() { register_rest_field('post', 'custom_field', [ 'get_callback' => function($post) { return get_post_meta($post['id'], 'custom_field', true); }, ]); });

JavaScript example to fetch posts from WordPress REST API: fetch('https://yourdomain.com/wp-json/wp/v2/posts').then(r => r.json()).then(posts => console.log(posts));

To set up CORS for your WordPress site, add headers like Access-Control-Allow-Origin: * in your server config or an .htaccess file for Apache.

Sequence to launch a basic headless WordPress site: 1) Confirm REST API enabled; 2) Develop frontend app to call API; 3) Add necessary PHP code for custom fields; 4) Configure CORS and authentication; 5) Test API and frontend integration thoroughly.

  1. Confirm WordPress version 4.7 or higher to have REST API enabled.
  2. Add custom REST API fields with PHP using register_rest_field if needed.
  3. Build frontend app to fetch and render JSON data.
  4. Configure server CORS headers to allow frontend domain.
  5. Test API endpoints using browser or Postman.
  6. Deploy frontend and confirm content renders correctly.

Questions people still ask

Can I use any frontend framework with headless WordPress?

Yes, any frontend that can make HTTP requests and render JSON can work with headless WordPress. React, Vue, Angular, or even plain JavaScript are common choices.

Is SEO harder with headless WordPress?

Yes, because you don’t get WordPress’s server-side rendered pages, you need to implement SEO in your frontend app, often using server-side rendering (SSR) or prerendering techniques.

Do I need to write custom PHP code for every headless WordPress project?

Not always. Basic REST API endpoints exist by default, but custom fields or routes often need PHP snippets to expose extra data.

How do I handle user authentication for private content?

You can use JWT, OAuth, or cookie authentication with plugins or custom code to secure REST API calls for logged-in users.

What if my API calls get blocked by CORS errors?

You must configure your WordPress server or hosting environment to include Access-Control-Allow-Origin headers that allow your frontend domain or wildcard (*) access.

Having built headless WordPress sites myself, the key is to test your REST API endpoints thoroughly and plan the frontend integration carefully.