| | 109 | * Retrieves the canonical URL for current post or post ID. |
| | 110 | * |
| | 111 | * @param int|WP_Post $post Optional. Post ID or post object. Default is the global `$post`. |
| | 112 | * |
| | 113 | * @return false|string The canonical URL or false if the post does not exist or has not been published yet. |
| | 114 | */ |
| | 115 | function get_canonical_url( $post = 0 ) { |
| | 116 | if ( ! is_object( $post ) ) { |
| | 117 | $post = get_post( $post ); |
| | 118 | } |
| | 119 | |
| | 120 | if ( 'publish' !== $post->post_status ) { |
| | 121 | return false; |
| | 122 | } |
| | 123 | |
| | 124 | $canonical_url = get_permalink( $post, false ); |
| | 125 | |
| | 126 | // If we're generating a canonical for the current page, make sure it has pagination if needed. |
| | 127 | if ( $post->ID === get_queried_object_id() ) { |
| | 128 | $page = get_query_var( 'page' ); |
| | 129 | if ( $page >= 2 ) { |
| | 130 | if ( '' == get_option( 'permalink_structure' ) ) { |
| | 131 | $canonical_url = add_query_arg( 'page', $page, $canonical_url ); |
| | 132 | } else { |
| | 133 | $canonical_url = trailingslashit( $canonical_url ) . user_trailingslashit( $page, 'single_paged' ); |
| | 134 | } |
| | 135 | } |
| | 136 | |
| | 137 | $cpage = get_query_var( 'cpage' ); |
| | 138 | if ( $cpage ) { |
| | 139 | $canonical_url = get_comments_pagenum_link( $cpage ); |
| | 140 | } |
| | 141 | } |
| | 142 | |
| | 143 | /** |
| | 144 | * Filter the canonical URL. |
| | 145 | * |
| | 146 | * @since |
| | 147 | * |
| | 148 | * @param string $string Canonical URL. |
| | 149 | * @param WP_Post $post Post object. Default is the global `$post`. |
| | 150 | */ |
| | 151 | return add_filter( 'get_canonical_url', $canonical_url, $post ); |
| | 152 | } |
| | 153 | |
| | 154 | /** |