From 346e47b1764efedcd27b09ae371ec6150a95853a Mon Sep 17 00:00:00 2001 From: Jake Spurlock Date: Tue, 8 Jun 2021 22:49:27 +0000 Subject: [PATCH] Permalinks: Limit pagination for posts with comments. Additionally, redirect pages back to the source page if comments don't exist. Props devrekli, carike, sumanm, mukesh27, chaion07, audrasjb, whyisjake, SergeyBiryukov. Fixes #50233. git-svn-id: https://develop.svn.wordpress.org/trunk@51118 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/canonical.php | 12 +++++++++-- .../phpunit/tests/link/wpGetCanonicalUrl.php | 21 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/canonical.php b/src/wp-includes/canonical.php index 184fb756e8..0eba17d60d 100644 --- a/src/wp-includes/canonical.php +++ b/src/wp-includes/canonical.php @@ -27,6 +27,7 @@ * or query in an attempt to figure the correct page to go to. * * @since 2.3.0 + * @since 5.8.0 Checks comment page count to limit pagination. * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * @global bool $is_IIS @@ -504,8 +505,15 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) { && ( 'newest' === $default_comments_page && $cpage > 0 || 'newest' !== $default_comments_page && $cpage > 1 ) ) { - $addl_path = ( ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '' ); - $addl_path .= user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . $cpage, 'commentpaged' ); + // Checks comment page count to limit pagination. + $per_page = get_option( 'comments_per_page' ); + + // Get the total number of pages for comments. + $comments_total_pages = ceil( ( $wp_query->post->comment_count ) / $per_page ); + if ( $cpage <= $comments_total_pages ) { + $addl_path = ( ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '' ); + $addl_path .= user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . $cpage, 'commentpaged' ); + } $redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] ); } diff --git a/tests/phpunit/tests/link/wpGetCanonicalUrl.php b/tests/phpunit/tests/link/wpGetCanonicalUrl.php index 5b7eddaada..a48f430b42 100644 --- a/tests/phpunit/tests/link/wpGetCanonicalUrl.php +++ b/tests/phpunit/tests/link/wpGetCanonicalUrl.php @@ -151,6 +151,27 @@ class Tests_Link_wpGetCanonicalUrl extends WP_UnitTestCase { $this->assertSame( $this->canonical_url_filter(), $canonical_url ); } + /** + * Limit pagination for comments. + * + * @ticket 50233 + */ + public function test_comments_limit_paged_with_plain_permalink_structure() { + $cpage = 5; + + $link = add_query_arg( + array( + 'cpage' => $cpage, + 'foo' => 'bar', + ), + get_permalink( self::$post_id ) + ); + + $this->go_to( $link ); + $expected = get_permalink( self::$post_id ) . '#comments'; + $this->assertSame( $expected, wp_get_canonical_url( self::$post_id ) ); + } + /** * Filter callback for testing of filter usage. *