Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.00% covered (success)
90.00%
9 / 10
100.00% covered (success)
100.00%
1 / 1
CRAP
n/a
0 / 0
wpcom_comment_page_canonical_url
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2/**
3 * Keep the canonical URL on the post when the request didn't ask for a comment page.
4 *
5 * @package automattic/jetpack-mu-wpcom
6 */
7
8/**
9 * `comments_template()` fills in `cpage` when the URL has none, and block templates run it
10 * before `wp_head` (legacy Comments block, WooCommerce reviews). See https://core.trac.wordpress.org/ticket/11856.
11 *
12 * @param string  $canonical_url The canonical URL.
13 * @param WP_Post $post          The post.
14 * @return string
15 */
16function wpcom_comment_page_canonical_url( $canonical_url, $post ) {
17    global $wp;
18
19    if ( ! get_query_var( 'cpage' ) || ! empty( $wp->query_vars['cpage'] ) || get_queried_object_id() !== $post->ID ) {
20        return $canonical_url;
21    }
22
23    $canonical_url = get_permalink( $post );
24    $page          = (int) get_query_var( 'page', 0 );
25    if ( $page >= 2 ) {
26        $canonical_url = get_option( 'permalink_structure' )
27            ? trailingslashit( $canonical_url ) . user_trailingslashit( $page, 'single_paged' )
28            : add_query_arg( 'page', $page, $canonical_url );
29    }
30
31    return $canonical_url;
32}
33add_filter( 'get_canonical_url', 'wpcom_comment_page_canonical_url', 1, 2 );