Support » Fixing WordPress » update_callback is not executing in register_rest_field

  • I am using below code to get/update custom post meta, get_callback is executing but update_callback is not executing

    add_action( 'rest_api_init', 'create_api_posts_meta_field' );
     
    function create_api_posts_meta_field() {
     
     // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
     register_rest_field( 'experience', 'subtitle', array(
     'get_callback' => 'get_post_meta_for_api',
     'update_callback'   => 'update_post_meta_for_exp',
     'schema' => array(
                'description' => 'Subtitle',
                'type' => 'string',
                'context' => array('view','edit')
            )
        )
     );
    }
    
    function update_post_meta_for_exp($value, $object, $field_name ) {
                    $havemetafield  = get_post_meta($object['id'], 'experience', false);
                    if ($havemetafield) {
                        $ret = update_post_meta($object['id'], 'subtitle', $value );
                        return true;
                    } else {
                        $ret = add_post_meta( $object['id'], 'subtitle', $value ,true );
                        return true;
                    }
                }
    
    function get_post_meta_for_api( $object ) {
     //get the id of the post object array
     $post_id = $object['id'];
     
     //return the post meta
     return get_post_meta( $post_id )["Subtitle"][0];
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • Joey

    (@leglesslizard)

    Hi,

    Apologies but dealing with the REST API isn’t something I’m overly familiar with. Have you done much logging to see what is actually the issue? Is the function not getting called at all or is it that something there is wrong? The first thing to do is add some debugging code to make sure the function is firing and then checking exactly what is going on inside the function.

    Kind regards,
    Joey

    Hi Joey,

    Thanks for reply, I tried everything but problem is update_callback is not getting called but get_callback is getting called, I debugged the code using netbeans and xdebug

    function update_post_meta_for_exp($value, $object, $field_name ) {
                    $havemetafield  = get_post_meta($object['id'], 'experience', false);
                    if ($havemetafield) {
                        $ret = update_post_meta($object['id'], 'subtitle', $value );
                        return true;
                    } else {
                        $ret = add_post_meta( $object['id'], 'subtitle', $value ,true );
                        return true;
                    }
                }

    This code never executes.

    varun,

    Have you managed to figure out what’s the issue?

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘update_callback is not executing in register_rest_field’ is closed to new replies.