Convert Figma logo to code with AI

airesvsg logoacf-to-rest-api

Exposes Advanced Custom Fields Endpoints in the WordPress REST API

1,338
114
1,338
149

Top Related Projects

1,501

Faust.js™ - The Headless WordPress Framework

:rocket: GraphQL API for WordPress

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.

11,289

The Block Editor project for WordPress and beyond. Plugin is available from the official repository.

A customizable, open-source ecommerce platform built on WordPress. Build any commerce solution you can imagine.

Quick Overview

ACF to REST API is a WordPress plugin that exposes Advanced Custom Fields (ACF) data to the WordPress REST API. It allows developers to easily access and manipulate custom field data through RESTful endpoints, enhancing the integration capabilities of WordPress with other applications and services.

Pros

  • Seamless integration of ACF data with the WordPress REST API
  • Simplifies the process of retrieving custom field data for headless WordPress setups
  • Supports various ACF field types, including complex ones like repeaters and flexible content
  • Customizable endpoints and field visibility options

Cons

  • Requires both ACF and the WordPress REST API to be active
  • May introduce performance overhead for large datasets or complex field structures
  • Limited built-in authentication options for accessing sensitive custom field data
  • Potential security risks if not properly configured

Code Examples

  1. Retrieving ACF fields for a post:
<?php
$response = wp_remote_get('https://example.com/wp-json/acf/v3/posts/123');
$acf_data = json_decode(wp_remote_retrieve_body($response), true);
print_r($acf_data);
  1. Updating an ACF field value via the REST API:
<?php
$data = array(
    'fields' => array(
        'field_name' => 'New Value'
    )
);

$args = array(
    'method'  => 'POST',
    'headers' => array('Content-Type' => 'application/json'),
    'body'    => json_encode($data)
);

$response = wp_remote_post('https://example.com/wp-json/acf/v3/posts/123', $args);
  1. Filtering ACF fields in the REST API response:
<?php
add_filter('acf/rest_api/post/get_fields', function($data) {
    // Remove sensitive fields
    unset($data['private_field']);
    return $data;
});

Getting Started

  1. Install and activate the ACF to REST API plugin in WordPress.

  2. Ensure that ACF and the WordPress REST API are active.

  3. Access ACF data via the REST API endpoints:

    • /wp-json/acf/v3/posts (for all posts)
    • /wp-json/acf/v3/posts/{post_id} (for a specific post)
    • /wp-json/acf/v3/pages/{page_id} (for pages)
    • /wp-json/acf/v3/users/{user_id} (for users)
    • /wp-json/acf/v3/terms/{taxonomy}/{term_id} (for terms)
  4. Customize the plugin behavior using WordPress filters and actions as needed.

Competitor Comparisons

1,501

Faust.js™ - The Headless WordPress Framework

Pros of Faustjs

  • Provides a complete headless WordPress framework, including server-side rendering and static site generation
  • Offers a more comprehensive solution for building modern web applications with WordPress as a headless CMS
  • Includes built-in TypeScript support and React hooks for easier development

Cons of Faustjs

  • Steeper learning curve due to its more complex architecture and features
  • Requires more setup and configuration compared to the simpler ACF to REST API plugin
  • May be overkill for projects that only need basic ACF field exposure in the REST API

Code Comparison

ACF to REST API:

add_filter('acf/rest_api/field_settings/show_in_rest', '__return_true');

Faustjs:

import { usePost } from '@faustjs/next';

const { post } = usePost();
console.log(post.acfFields.customField);

The ACF to REST API plugin simply exposes ACF fields in the WordPress REST API, while Faustjs provides a more comprehensive framework for building headless WordPress applications with React and Next.js, including utilities for accessing ACF fields.

:rocket: GraphQL API for WordPress

Pros of wp-graphql

  • Offers a more flexible and efficient querying system with GraphQL
  • Provides a single endpoint for all data requests, reducing network overhead
  • Allows for introspection, making it easier to explore and understand the API schema

Cons of wp-graphql

  • Requires learning GraphQL, which may have a steeper learning curve for some developers
  • May require additional setup and configuration compared to REST API solutions
  • Potentially more complex to implement for simple use cases

Code Comparison

wp-graphql:

query {
  posts {
    nodes {
      id
      title
      content
    }
  }
}

acf-to-rest-api:

GET /wp-json/wp/v2/posts?_fields=id,title,content

The wp-graphql example demonstrates a GraphQL query to fetch posts with specific fields, while the acf-to-rest-api example shows a REST API request to achieve a similar result. The GraphQL approach allows for more precise data selection and nested queries, while the REST API is more straightforward but may require multiple requests for complex data structures.

wp-graphql offers more flexibility and efficiency in data fetching, especially for complex queries, but may require more initial setup and learning. acf-to-rest-api provides a simpler approach that integrates easily with existing WordPress REST API knowledge but may be less efficient for complex data requirements.

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.

Pros of Apollo Client

  • Comprehensive GraphQL client with advanced features like caching and state management
  • Extensive ecosystem with integrations for popular frameworks and libraries
  • Strong TypeScript support and developer tooling

Cons of Apollo Client

  • Steeper learning curve due to its complexity and feature-rich nature
  • Potentially overkill for simple GraphQL implementations
  • Larger bundle size compared to lightweight alternatives

Code Comparison

ACF to REST API:

add_filter( 'acf/rest_api/field_settings/show_in_rest', '__return_true' );

Apollo Client:

const client = new ApolloClient({
  uri: 'https://api.example.com/graphql',
  cache: new InMemoryCache()
});

Summary

ACF to REST API is a WordPress plugin that exposes Advanced Custom Fields data to the REST API, making it easier to access custom field data in headless WordPress setups. It's lightweight and focused on a specific use case.

Apollo Client, on the other hand, is a comprehensive GraphQL client for JavaScript applications. It offers powerful features like caching, state management, and integrations with various frameworks. While more complex, it provides a robust solution for GraphQL-based applications across different platforms.

The choice between these libraries depends on the specific project requirements, with ACF to REST API being more suitable for WordPress-centric projects and Apollo Client for larger, GraphQL-focused applications.

11,289

The Block Editor project for WordPress and beyond. Plugin is available from the official repository.

Pros of Gutenberg

  • Comprehensive block-based editing system for WordPress
  • Actively maintained by the WordPress core team
  • Extensive documentation and community support

Cons of Gutenberg

  • Steeper learning curve for developers
  • May require significant changes to existing themes and plugins
  • Larger codebase and potentially slower performance

Code Comparison

Gutenberg (React-based block registration):

registerBlockType('my-plugin/my-block', {
    title: 'My Block',
    icon: 'smiley',
    category: 'common',
    edit: ({ attributes, setAttributes }) => {
        // Block edit component
    },
    save: ({ attributes }) => {
        // Block save component
    },
});

ACF to REST API (PHP-based field registration):

function register_acf_field() {
    acf_add_local_field_group(array(
        'key' => 'group_1',
        'title' => 'My Custom Field',
        'fields' => array(
            array(
                'key' => 'field_1',
                'label' => 'Text Field',
                'name' => 'text_field',
                'type' => 'text',
            )
        ),
        'location' => array(
            array(
                array(
                    'param' => 'post_type',
                    'operator' => '==',
                    'value' => 'post',
                ),
            ),
        ),
    ));
}
add_action('acf/init', 'register_acf_field');

While Gutenberg focuses on block-based content creation, ACF to REST API simplifies exposing custom fields to the WordPress REST API. Gutenberg offers a more comprehensive editing experience, while ACF to REST API provides a straightforward solution for extending the REST API with custom field data.

A customizable, open-source ecommerce platform built on WordPress. Build any commerce solution you can imagine.

Pros of WooCommerce

  • Comprehensive e-commerce solution with extensive features
  • Large community and ecosystem of extensions
  • Regular updates and active development

Cons of WooCommerce

  • Larger codebase and potentially higher resource usage
  • Steeper learning curve for customization
  • May include unnecessary features for simpler projects

Code Comparison

WooCommerce (product registration):

function register_product_type() {
    class WC_Product_Custom extends WC_Product {
        public function __construct( $product ) {
            $this->product_type = 'custom';
            parent::__construct( $product );
        }
    }
}
add_action( 'init', 'register_product_type' );

ACF to REST API (field registration):

function register_acf_field() {
    acf_add_local_field_group(array(
        'key' => 'group_custom',
        'title' => 'Custom Field',
        'fields' => array(
            array(
                'key' => 'field_custom',
                'label' => 'Custom Field',
                'name' => 'custom_field',
                'type' => 'text',
            )
        ),
        'location' => array(
            array(
                array(
                    'param' => 'post_type',
                    'operator' => '==',
                    'value' => 'post',
                ),
            ),
        ),
    ));
}
add_action( 'acf/init', 'register_acf_field' );

The code examples demonstrate the different focus of each project: WooCommerce for e-commerce functionality and ACF to REST API for custom field integration with the WordPress REST API.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

ACF to REST API

Exposes Advanced Custom Fields Endpoints in the WordPress REST API

https://wordpress.org/plugins/acf-to-rest-api/

Installation

  1. Copy the acf-to-rest-api folder into your wp-content/plugins folder
  2. Activate the ACF to REST API plugin via the plugin admin page

Endpoints

EndpointREADABLEEDITABLE
/wp-json/acf/v3/posts 🆕✅❌
/wp-json/acf/v3/posts/{id}✅✅
/wp-json/acf/v3/posts/{id}/{field-name}✅✅
/wp-json/acf/v3/pages 🆕✅❌
/wp-json/acf/v3/pages/{id}✅✅
/wp-json/acf/v3/pages/{id}/{field-name}✅✅
/wp-json/acf/v3/users 🆕✅❌
/wp-json/acf/v3/users/{id}✅✅
/wp-json/acf/v3/users/{id}/{field-name}✅✅
/wp-json/acf/v3/{taxonomy} 🆕✅❌
/wp-json/acf/v3/{taxonomy}/{id} 🆕✅✅
/wp-json/acf/v3/{taxonomy}/{id}/{field-name} 🆕✅✅
/wp-json/acf/v3/comments 🆕✅❌
/wp-json/acf/v3/comments/{id}✅✅
/wp-json/acf/v3/comments/{id}/{field-name}✅✅
/wp-json/acf/v3/media 🆕✅❌
/wp-json/acf/v3/media/{id}✅✅
/wp-json/acf/v3/media/{id}/{field-name}✅✅
/wp-json/acf/v3/{post-type} 🆕✅❌
/wp-json/acf/v3/{post-type}/{id} 🆕✅✅
/wp-json/acf/v3/{post-type}/{id}/{field-name} 🆕✅✅
/wp-json/acf/v3/options/{id} 🆕✅✅
/wp-json/acf/v3/options/{id}/{field-name} 🆕✅✅

Filters

FilterArgument(s)
acf/rest_api/idmixed ( string, integer, boolean ) $id
string $type 🆕
string $controller 🆕
acf/rest_api/keystring $key
WP_REST_Request $request
string $type
acf/rest_api/item_permissions/getboolean $permission
WP_REST_Request $request
string $type
acf/rest_api/item_permissions/updateboolean $permission
WP_REST_Request $request
string $type
acf/rest_api/{type}/prepare_itemmixed ( array, boolean ) $item
WP_REST_Request $request
acf/rest_api/{type}/get_fieldsmixed ( array, WP_REST_Request ) $data
mixed ( WP_REST_Request, NULL ) $request
acf/rest_api/field_settings/show_in_rest 🆕boolean $show
acf/rest_api/field_settings/edit_in_rest 🆕boolean $edit

Basic example of how to use the filters, in this case I will set a new permission to get the fields

add_filter( 'acf/rest_api/item_permissions/get', function( $permission ) {
  return current_user_can( 'edit_posts' );
} );

Deprecated filters

FilterArgument(s)
acf/rest_api/typestring $type
acf/rest_api/typesarray $types
acf/rest_api/default_rest_baseboolean $default
string $type

Request API version

See below how to select the Request API Version.

  1. Open the plugins page;
  2. Click the settings link under the pluing name ( ACF to REST API );
  3. Select your version in the ACF to REST API session;
  4. Click in the button Save changes.

The other alternative is to define the constant ACF_TO_REST_API_REQUEST_VERSION in your wp-config.php

define( 'ACF_TO_REST_API_REQUEST_VERSION', 2 );

Field Settings

In this version is possible to configure the field options via admin.

The options are enabled using the filters below, by default theses options are disabled.

// Enable the option show in rest
add_filter( 'acf/rest_api/field_settings/show_in_rest', '__return_true' );

// Enable the option edit in rest
add_filter( 'acf/rest_api/field_settings/edit_in_rest', '__return_true' );

Editing the fields

The fields should be sent into the key fields.

Action: http://localhost/wp-json/acf/v3/posts/1

<form action="http://localhost/wp-json/acf/v3/posts/1" method="POST">
  <?php 
    // https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
    wp_nonce_field( 'wp_rest' ); 
  ?>
  <label>Site: <input type="text" name="fields[site]"></label>
  <button type="submit">Save</button>
</form>

Action: http://localhost/wp-json/wp/v2/posts/1

<form action="http://localhost/wp-json/wp/v2/posts/1" method="POST">
  <?php 
    // https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
    wp_nonce_field( 'wp_rest' ); 
  ?>
  <label>Title: <input type="text" name="title"></label>
  <h3>ACF</h3>
  <label>Site: <input type="text" name="fields[site]"></label>
  <button type="submit">Save</button>
</form>

Use the filter acf/rest_api/key to change the key fields.

add_filter( 'acf/rest_api/key', function( $key, $request, $type ) {
  return 'acf_fields';
}, 10, 3 );

Now, the fields should be sent into the key acf_fields

<form action="http://localhost/wp-json/acf/v3/posts/1" method="POST">
  <?php 
    // https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
    wp_nonce_field( 'wp_rest' ); 
  ?>
  <label>Site: <input type="text" name="acf_fields[site]"></label>
  <button type="submit">Save</button>
</form>

Examples

Sample theme to edit the ACF Fields.

https://github.com/airesvsg/acf-to-rest-api-example

To-do list 🆕

https://github.com/airesvsg/to-do-list-acf-to-rest-api

Get ACF Fields Recursively🆕

https://github.com/airesvsg/acf-to-rest-api-recursive

More details:

Cache

Enable caching for WordPress REST API and increase speed of your application.

https://github.com/airesvsg/wp-rest-api-cache