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
This commit is contained in:
Jake Spurlock 2021-06-08 22:49:27 +00:00
parent 7b2793e242
commit 346e47b176
2 changed files with 31 additions and 2 deletions

View File

@ -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'] );
}

View File

@ -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.
*