Search code examples
wordpresscustom-post-typewordpress-rest-api

Adding post_parent to a particular post type in Wordpress Rest Api


How can we add a post_parent field to a particular post type in wordpress?


Solution

  • Use below code will add post_perent

    add_action( 'rest_api_init', array( $this, 'add_post_parent_to_posts_route' ) );
    
    function add_post_parent_to_posts_route() {
            $args = array(
                'get_callback'    => array( $this, 'get_post_parent' ),
                'update_callback' => array( $this, 'set_post_parent' ),
                'schema'          => null,
            );
            register_rest_field( 'post', 'parent', $args );
            register_rest_field( 'attachment', 'parent', $args );
        }
        function get_post_parent( $data ) {
            $post = get_post( $data['id'] );
            return $post->post_parent;
        }
        function set_post_parent( $value, $post, $attr, $request, $object_type ) {
            //permission to edit built-in post types is handled for us
            wp_update_post(
                array(
                    'ID'          => $post->ID,
                    'post_parent' => $value,
                )
            );
        }
    

    Tested and works well.