php – Custom rest fields not loaded in rest api cpt response

Question

I have a custom endpoint that will be used from my vue app to load custom post type I’ve registered using a custom plugin. I need to add some custom fields to the response when the posts are loaded and I’ve used this code

    public function register_custom_endpoints() 
    {
        register_rest_route( 
            'rest/v1', 
            '/loadMessages', 
            array(
                'methods' => 'GET',
                'callback' => array( $this, 'get_comunications' ), 
                /*'permissions_callback' => function(){
                    if( !is_user_logged_in() ) {
                        return new WP_Error(
                            'rest_not_logged_in',
                            __( 'You are not currently logged in.' ),
                            array( 
                                'status' => 403 
                            )
                        );
                    }
                }*/
            )
        );
    }

    public function register_custom_fields()
    {
        register_rest_field( 
            array(
                'comunications',
                'academy'
            ), 
            'post_meta', 
            array(
                'get_callback' => array( $this, 'get_custom_post_meta' )
            ) 
        );
    }
  

And these are the callbacks

    public function get_comunications( WP_REST_Request $request )
    {
        /*if( !wp_verify_nonce( sanitize_text_field( $request->get_header( 'X-WP-Nonce' ) ), 'wp_rest' ) ){
            return new WP_Error(  
                'expired_or_invalid_nonce',
                __( 'Invalid nonce.' ),
                array(
                    'status' => 403
                )
            );
        }*/

        $q = new WP_Query( 
            array(
                'post_type' => 'comunications',
                'posts_per_page' => -1
            ) 
        );
        return new WP_REST_Response( $q->posts, 200 ); 
    }

    public function get_custom_post_meta( $object )
    {
        $post_id = $object['id'];
        //return get_post_meta( $post_id );
        return $post_id;
    }

The posts at the moment don’y have any post meta but I expect to see the empty field into the response when posts are loaded. Is there something wrong with my code?

0
ICTDEV 2 weeks 2023-09-18T03:35:17-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse