Created
May 22, 2026 15:18
-
-
Save damiencarbery/038aec4072226f533c761a17ab62362e to your computer and use it in GitHub Desktop.
Change a REST API field value - Change the value of a field in a REST API endpoint. https://www.damiencarbery.com/2026/05/change-a-rest-api-field-value/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| Plugin Name: REST API - change field value | |
| Plugin URI: https://www.damiencarbery.com | |
| Description: Change the value of a field in a REST API endpoint. | |
| Author: Damien Carbery | |
| Version: 0.1.20260522 | |
| */ | |
| class RestApiAddField { | |
| private $post_type; | |
| private $field_to_change; | |
| // Returns an instance of this class. | |
| public static function get_instance() { | |
| if ( null == self::$instance ) { | |
| self::$instance = new self; | |
| } | |
| return self::$instance; | |
| } | |
| // Initialize the plugin variables. | |
| public function __construct() { | |
| // Set the post type that we will access. | |
| $this->post_type = 'post'; | |
| // And the REST API field we are changing. | |
| $this->field_to_change = 'link'; | |
| $this->init(); | |
| } | |
| // Set up WordPress specfic actions. | |
| public function init() { | |
| add_action( 'rest_api_init', array( $this, 'change_rest_api_link_field' ) ); | |
| } | |
| public function change_rest_api_link_field() { | |
| register_rest_field( $this->post_type, $this->field_to_change, array( | |
| 'get_callback' => array( $this, 'get_link_for_rest_api' ), | |
| ) | |
| ); | |
| } | |
| public function get_link_for_rest_api( $object, $request ) { | |
| //error_log( '$request: ' . var_export( $request, true ) ); | |
| //error_log( '$object: ' . var_export( $object, true ) ); | |
| // Get the id of the post from the object array if needed. | |
| //$post_id = $object['id']; | |
| if ( $this->field_to_change == $request ) { | |
| return str_replace( home_url(), 'https://example.com', $object['link'] ); | |
| } | |
| // If you use the same callback to process another field then check $request. | |
| /*if ( 'guid' == $request ) { | |
| return $object[ $request ] . '&extra=more_data'; | |
| }*/ | |
| return $object[ $request ]; | |
| } | |
| } | |
| $RestApiAddField = new RestApiAddField(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment