Search code examples
phpwordpresscustom-wordpress-pageswordpress-rest-api

wordpress make changes to post api


We are using wordpress for blogs (hosted via Godaddy). I am not a wordpress developer and hence this basic question. We have the wordpress post api like blog.domainname.com/wp-json/wp/v2/posts. This returns a json object of most of the fields. Now i have added a custom field to be returned with this object. i have seen lot of videos and study on what changes that needs to be done especially the one here. https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/

My Question is - Where do I make these changes? What file do I need add these changes? I am using WP as an admin. I installed a File Explorer plugin and I am able to see three main folders - wp-admin, wp-content, wp-includes.

Is there a particular file i need to make changes? Based on my learning - i wrote the following snippet. not sure where to add this :(

function addCustomField_register_fields() {

register_rest_field('post',
        'custom_Field_name',
        array(
            'get_callback'      =>'get_custom_field',
            'update_callback'   => null,
            'schema'        => null
        ));

    }

function get_custom_field($object, $field_name , $request) {
    return get_post('custom_field');
    }

add_action('rest_api_init', 'addCustomField_register_fields');

Also would appreciate if you can let me know if my method is correct.


Solution

  • Typically theme customisations are added to the functions.php file in the root directory of your active theme.

    As for your code, what are you trying to do? Your callback in particular doesn't look like it will work. get_post() loads a WordPress post by ID. 'custom_field' isn't a valid post ID, so this will always fail.