Modify the WordPress REST response

Last Updated on: 28th September 2022, 02:46 pm

I have searched high and low for a way to remove elements from the WordPress REST API response, but only found poor results. In the end I came up with my own. Here is how to remove elements from the WordPress REST API response.

<?php
/**
 * Plugin Name: CS Modify REST Response
 * Description: Remove data from the REST response. 
 * Author: Con Schneider
 * Author URI: https://conschneider.de/
 * License: GPLv2 or later
 * Text Domain: voilamodify-
 * Version: 0.3
 * Domain Path: /languages/
 */

if ( ! defined( 'WPINC' ) ) { die; }

function cs_rest_prepare_post( $data, $post, $request ) {

    $_data = $data->data; // get the data object of the REST response. Dump this to see which elements you can use for a control statement. 
    $my_condition = $_data['category']; // We will remove posts from a certain category. 

    if ( is_user_logged_in() ) {
        return $data; // Make sure only logged in users see JSON data. Optional. 
    }

    if ( in_array( 'some_category', $my_condition) ) {
        $_data = []; // Remove all posts from the 'some_category' category.
    }
    $data->data = $_data;
    return $data;
}
add_filter( 'rest_prepare_post', 'cs_rest_prepare_post', 10, 3 );

Happy coding.

Leave a Reply

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

Con Schneider