在 Wordpress Rest Api 中将 post_parent 添加到特定的 post 类型

Adding post_parent to a particular post type in Wordpress Rest Api

我们如何将 post_parent 字段添加到 wordpress 中的特定 post 类型?

使用下面的代码将添加 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,
            )
        );
    }

经过测试并且运行良好。