You are already using the correct Gutenberg/JS code, but it’s a limitation in the REST API which exposes the parent
field only for hierarchical post types like page
. But you can force the field to appear in the REST API responses via register_rest_field()
— example for a my_cpt
post type:
register_rest_field( 'my_cpt', 'parent', array(
'schema' => array(
'description' => __( 'The ID for the parent of the post.' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
) );
Alternatively, you can use the rest_prepare_<post type>
hook to just add the parent
in the response:
add_filter( 'rest_prepare_my_cpt', function ( $response, $post ) {
$data = $response->get_data();
$data['parent'] = $post->post_parent;
$response->set_data( $data );
return $response;
}, 10, 2 );
But if you want to allow editing the parent via the REST API, then the first option is preferred.