Transform WordPress into a Backend with the Power of REST API

|
7 mins reading time

WordPress is not just a website creation system or a content management tool; it also features an API that extends its capabilities for development and integration with other systems. Whether you want to build an application or connect with various services, the WordPress API can assist you. This article will introduce you to the WordPress API and show you how to make the most of its functionality.

More People Are Using WordPress as a Backend

In recent years, using WordPress as a Backend has become increasingly popular. This trend is primarily driven by developers shifting towards React and Vue.js for building Frontends, while leveraging the WordPress API (REST API) for seamless integration with these frameworks. As a result, WordPress is no longer just a content management system (CMS) but has evolved into a powerful tool that can serve as a Backend for storing and transmitting data to the Frontend.

What Does the WordPress API Offer Out of the Box?

In WordPress REST API version 2 (/v2), essential tools for creating and managing data through the API are built directly into the system. This allows developers to easily access and manage data on the website. Working with the REST API involves using specific URL structures to retrieve data in JSON format.


An example of a URL used to access data through the API would look like this:

https://yoursite.com/wp-json/wp/v2/

In this URL structure:

  • https://yoursite.com: This is the domain of your WordPress website.
  • /wp-json: This is the base path for accessing the WordPress REST API.
  • /wp/v2/: This is the specific path indicating that you are using version 2 of the WordPress REST API.

By appending specific paths to the URL, you can access various types of data such as posts, pages, metadata, and user information. For example:

  • /posts: To retrieve all posts.
  • /pages: To retrieve all pages.
  • /users: To retrieve user information.


When you access these URLs, you will receive the corresponding data in JSON format, which can then be utilized in your application or Frontend web development immediately.​⬤

Examples of Accessing the REST API

Retrieving Posts

https://yoursite.com/wp-json/wp/v2/posts

Retrieving Posts by ID

https://yoursite.com/wp-json/wp/v2/posts/{ID}

Retrieving Pages

https://yoursite.com/wp-json/wp/v2/pages
ตัวอย่างข้อมูลที่ได้จาก Rest API ของการดึงโพสต์
Example of Data Retrieved from the REST API for a Post

How to Customize the API Yourself

Here’s an example of how to create a custom field called “pin” in the /v2/posts API: If you want to add a custom field to the WordPress REST API without using additional plugins, you can use the register_rest_field function along with the rest_api_init hook directly in your theme’s functions.php file. This method allows you to manage the data effectively.

Example of how to create a custom field called “pin” in the /v2/posts API:

function add_custom_fields_to_post_api() {
    // ฟังก์ชั่นสำหรับเพิ่ม field ใน API
    register_rest_field(
        'post', // ประเภทของข้อมูลที่ต้องการเพิ่มฟิลด์
        'pin', // ชื่อฟิลด์ที่ต้องการเพิ่มใน API
        array(
            'get_callback'    => 'get_post_meta_for_api',
            'schema'          => null,
        )
    );
}

function get_post_meta_for_api($object) {
    return get_post_meta($object['id'], 'pin', true);
}

add_action('rest_api_init', 'add_custom_fields_to_post_api');

Example of how to create a new REST API endpoint called /v2/messages in WordPress

function register_custom_api_routes() {
    register_rest_route(
        'v2', // เวอร์ชั่น
        '/messages', // ชื่อ Route
        array(
            'methods'  => 'GET', // HTTP (GET, POST, etc.)
            'callback' => 'get_custom_messages', // ฟังก์ชั่นที่ return        )
    );
}

add_action('rest_api_init', 'register_custom_api_routes');

function get_custom_messages() {
    // รีเทิร์นข้อมูลสำหรับ API
    $messages = array(
        array(
            'id'      => 1,
            'message' => 'Hello, this is the first custom message!',
        ),
        array(
            'id'      => 2,
            'message' => 'Here is another custom message.',
        ),
    );

    return rest_ensure_response($messages);
}

Adding ACF Data to the REST API

ปรับ ACF ให้แสดงใน API ไปด้วย
Adjusting ACF to Include Fields in the API

ในเวอร์ชั่นใหม่ของ ACF มีฟีเจอร์ที่ให้คุณสามารถเปิดใช้งานการแนบข้อมูลฟิลด์ไปกับ REST API ได้ทันที โดยคุณสามารถเปิดใช้งานฟีเจอร์นี้ได้ที่หน้าการตั้งค่าของฟิลด์กรุ๊ป ACF > Field Group > Group Settings > Show in REST API

Once enabled, ACF will link the specified fields to the corresponding Post Type or Page. When the REST API is called, these fields will be automatically included in the API response.

How to Enhance the Security of the REST API

The REST API provided by WordPress is publicly accessible by default. However, there are several methods you can use to protect it from general access, such as using authentication, tokens, or creating a whitelist. In this example, I’ll demonstrate the simplest method, which is using a whitelist to restrict access.

Example of how to implement IP-based whitelisting to restrict access to the API:

function restrict_api_access_by_ip($result) {
    // รายการ IP ที่อนุญาต
    $allowed_ips = array(
        '123.456.789.000', // ใส่ข้อมูล IP ที่อนุญาตให้ใช้ API
        '111.222.333.444',
    );

    // ดึง IP ที่ทำการเรียกใช้ API
    $ip_address = $_SERVER['REMOTE_ADDR'];

    // ตรวจสอบ IP ถ้าไม่ได้อยู่ในรายกาารที่ไม่อนุญาตให้แสดง error
    if (!in_array($ip_address, $allowed_ips)) {
        return new WP_Error('rest_forbidden', 'Your IP address is not allowed to access this API.', array('status' => 403));
    }

    return $result;
}

add_filter('rest_authentication_errors', 'restrict_api_access_by_ip');

Example of how to implement domain-based whitelisting to restrict access to the WordPress REST API by checking the domain of the request:

function restrict_api_access_by_domain($result) {
    // รายการ Domain ที่อนุญาต
    $allowed_domains = array(
        'https://allowed-domain.com',
        'https://another-allowed-domain.com',
    );

    // ดึง Domaiin ที่ทำการเรียกใช้ API
    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';

    // ตรวจสอบ Domain ถ้าไม่ได้อยู่ในรายกาารที่ไม่อนุญาตให้แสดง error
    if (!in_array($origin, $allowed_domains)) {
        return new WP_Error('rest_forbidden', 'Your domain is not allowed to access this API.', array('status' => 403));
    }

    return $result;
}

add_filter('rest_authentication_errors', 'restrict_api_access_by_domain');

If you want to learn more about using the WordPress REST API, you can read the official documentation directly on the WordPress website. It provides comprehensive guides and examples at: https://developer.wordpress.org/rest-api/

Designil PDPA Banner Thai Woo AIO Banner

author - aum watcharapon
Aum Watcharapon
👨🏻‍💻 WordPress Expertiser

Subscribe to newsletter

doaction will send notifications when new articles are available on the website, and you can unsubscribe at any time.

More Articles

Enhance Security: Add a Layer by Hiding wp-login for WordPress

Not hiding the wp-login.php page on a WordPress site in production is a critical security concern, even though it is just one of many security measures that should be implemented. Hiding the wp-login.php page can reduce the risk of brute force attacks, where attackers attempt to guess passwords to gain access. This not only increases the risk of being hacked but can also burden the server due to continuous password-guessing attacks. If you prefer to keep the wp-login.php page accessible, it’s advisable to configure login attempt limits. If the number of failed attempts exceeds the defined limit, the IP address can be blocked. This approach is better than leaving the page open without any restrictions, as bots often automatically search for wp-login.php and attempt to log in. Changing the login page URL can also slow down bots, making it harder for them to locate the login page, thus enhancing website security. WordPress Brute Force Protection Recommendations According to the official WordPress recommendations for brute force protection, the following methods are suggested: • Creating a .htpasswd file to restrict direct access to wp-login.php. • Hiding access to […]

Read more

Why is Meta Box a recommended plugin for managing fields in WordPress?

Recently, the WordPress community has been shaken by a major conflict between WordPress and WP Engine, which has left many surprised and questioning the direction of these two giants. This conflict has not only impacted WP Engine’s hosting services but has also extended to the blocking of related ACF plugins and their ban from the WordPress.org directory. This means users within the WP Engine ecosystem may no longer have access to updates or support from WordPress. One promising alternative is the Meta Box plugin, which offers flexible and efficient field management. In this article, we’ll introduce you to Meta Box, explore its features, and explain why it has become a popular topic of discussion recently. Differences Between ACF and Meta Box The ACF (Advanced Custom Fields) plugin, in its pro version, comes with a wide range of basic capabilities, such as managing Options Pages, fields, and Post Types […]

Read more

If you have any questions or need advice about WordPress, feel free to ask.

Office

  • © do action co., ltd. 2024
    66 Soi Petchkasem 98/1, Petchkasem Road,
    Bangkhae Nuea, Bangkhae,
    Bangkok, Thailand
    10160
PDPA Icon

Our website uses cookies to enhance your user experience.

Privacy Preferences

คุณสามารถเลือกการตั้งค่าคุกกี้โดยเปิด/ปิด คุกกี้ในแต่ละประเภทได้ตามความต้องการ ยกเว้น คุกกี้ที่จำเป็น

Allow All
Manage Consent Preferences
  • Always Active

Save