How do you add custom fields defined in posts to the rest API responses in wordpress

前端 未结 4 1052
不知归路
不知归路 2020-12-08 17:28

I want to do this without using any sort of plugin since these are both core wordpress features (custom fields and the REST API). Here is the documentation for custom fields

相关标签:
4条回答
  • 2020-12-08 18:13

    Use this plugin for this solution: https://wordpress.org/plugins/acf-to-rest-api/ as it allows you to expose the Advanced Custom Fields into their own JSON response via new endpoints listed here https://github.com/airesvsg/acf-to-rest-api#endpoints. You can then forkJoin the two observables (if using Angular) and utilize the combined response toward your purpose.

    0 讨论(0)
  • 2020-12-08 18:20

    I found the REST API Custom Fields plugin useful for this.

    0 讨论(0)
  • 2020-12-08 18:23

    First you need to register_rest_fields to adding custom endpoints in WP REST API JSON Response

    add_action( 'rest_api_init', 'add_custom_fields' );
    function add_custom_fields() {
    register_rest_field(
    'post', 
    'custom_fields', //New Field Name in JSON RESPONSEs
    array(
        'get_callback'    => 'get_custom_fields', // custom function name 
        'update_callback' => null,
        'schema'          => null,
         )
    );
    }
    

    Then define your functions to get custom fields

    function get_custom_fields( $object, $field_name, $request ) {
    //your code goes here
    return $customfieldvalue;
    }
    

    Tested on local site

    0 讨论(0)
  • 2020-12-08 18:30

    Just add it in your CMS and then it should be available inside your WP REST API.

    0 讨论(0)
提交回复
热议问题