diff --git a/src/wp-includes/link-template.php b/src/wp-includes/link-template.php index aabf7bc69db79..a5437b2575a89 100644 --- a/src/wp-includes/link-template.php +++ b/src/wp-includes/link-template.php @@ -4205,8 +4205,11 @@ function wp_get_shortlink( $id = 0, $context = 'post', $allow_slugs = true ) { $post_id = 0; if ( 'query' === $context && is_singular() ) { - $post_id = get_queried_object_id(); - $post = get_post( $post_id ); + $queried_object = get_queried_object(); + if ( $queried_object instanceof WP_Post ) { + $post = $queried_object; + $post_id = $queried_object->ID; + } } elseif ( 'post' === $context ) { $post = get_post( $id ); if ( ! empty( $post->ID ) ) { diff --git a/tests/phpunit/tests/link.php b/tests/phpunit/tests/link.php index 04f4efb5b5582..5619a4b69e4ad 100644 --- a/tests/phpunit/tests/link.php +++ b/tests/phpunit/tests/link.php @@ -81,6 +81,32 @@ public function test_wp_get_shortlink_with_home_page() { $this->assertSame( home_url( '/' ), wp_get_shortlink( $post_id, 'post' ) ); } + /** + * @ticket 66348 + */ + public function test_wp_get_shortlink_with_query_context() { + $post_id = self::factory()->post->create(); + + $this->go_to( get_permalink( $post_id ) ); + + $this->assertSame( home_url( '?p=' . $post_id ), wp_get_shortlink( 0, 'query' ) ); + } + + /** + * @ticket 66348 + */ + public function test_wp_get_shortlink_with_query_context_and_non_post_queried_object() { + $post_id = self::factory()->post->create(); + + $this->go_to( get_permalink( $post_id ) ); + + // A singular query whose queried object is not a post, with an ID that does not resolve to one. + $GLOBALS['wp_query']->queried_object = (object) array( 'ID' => PHP_INT_MAX ); + $GLOBALS['wp_query']->queried_object_id = PHP_INT_MAX; + + $this->assertSame( '', wp_get_shortlink( 0, 'query' ) ); + } + /** * @ticket 30910 */