Last active
December 9, 2020 11:28
-
-
Save igmoweb/ddb04b5441235c55095edcd75a69997b to your computer and use it in GitHub Desktop.
This file contains 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 | |
const FIELD_NAME = 'field_name'; | |
add_action( 'rest_api_init', __NAMESPACE__ . '\\register_api_fields' ); | |
function register_api_fields() { | |
register_rest_field( | |
'post', | |
FIELD_NAME, | |
[ | |
'get_callback' => function ( $object ) { | |
$post_id = $object['id'] ?? 0; | |
if ( ! current_user_can( 'edit_post', $post_id ) ) { | |
return ''; | |
} | |
return 'something'; | |
}, | |
'update_callback' => function ( $value, $object, $field_name ) { | |
return true; | |
}, | |
'schema' => array( | |
'type' => 'string', | |
'arg_options' => array( | |
'sanitize_callback' => function ( $value ) { | |
// Make the value safe for storage. | |
return sanitize_text_field( $value ); | |
}, | |
'validate_callback' => function ( $value ) { | |
// Valid if it contains exactly 10 English letters. | |
return (bool) preg_match( '/\A[a-z]{10}\Z/', $value ); | |
}, | |
), | |
), | |
] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment