From b8cdf1be50ab8d6cfb7b3e594bc8558f64376acf Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Sat, 24 Oct 2020 13:18:50 +0000 Subject: [PATCH] REST API: Support generating comment up links to custom posts controllers. The comments controller now uses the `rest_get_route_for_post` function introduced in WordPress 5.5 to generate the link. This function is filterable to allow for custom controllers to properly define their REST API route. Props dsifford, TimothyBlynJacobs. Fixes #44152. git-svn-id: https://develop.svn.wordpress.org/trunk@49299 602fd350-edb4-49c9-b593-d223f7449a82 --- .../endpoints/class-wp-rest-comments-controller.php | 10 ++++------ .../tests/rest-api/rest-comments-controller.php | 4 ++++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php index b921144684..85c8f22e8b 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php @@ -1159,14 +1159,12 @@ class WP_REST_Comments_Controller extends WP_REST_Controller { } if ( 0 !== (int) $comment->comment_post_ID ) { - $post = get_post( $comment->comment_post_ID ); - - if ( ! empty( $post->ID ) ) { - $obj = get_post_type_object( $post->post_type ); - $base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name; + $post = get_post( $comment->comment_post_ID ); + $post_route = rest_get_route_for_post( $post ); + if ( ! empty( $post->ID ) && $post_route ) { $links['up'] = array( - 'href' => rest_url( 'wp/v2/' . $base . '/' . $comment->comment_post_ID ), + 'href' => rest_url( $post_route ), 'embeddable' => true, 'post_type' => $post->post_type, ); diff --git a/tests/phpunit/tests/rest-api/rest-comments-controller.php b/tests/phpunit/tests/rest-api/rest-comments-controller.php index ba67234a23..f61f438b05 100644 --- a/tests/phpunit/tests/rest-api/rest-comments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-comments-controller.php @@ -3254,6 +3254,10 @@ class WP_Test_REST_Comments_Controller extends WP_Test_REST_Controller_Testcase array_keys( $links ) ); + if ( $comment->comment_post_ID ) { + $this->assertEquals( rest_url( '/wp/v2/posts/' . $comment->comment_post_ID ), $links['up'][0]['href'] ); + } + if ( 'edit' === $context ) { $this->assertSame( $comment->comment_author_email, $data['author_email'] ); $this->assertSame( $comment->comment_author_IP, $data['author_ip'] );