wp_get_canonical_url() WordPress Function

The wp_get_canonical_url() function is used to retrieve the canonical URL for a post or page. This is the URL that is used as the permanent link for a post or page.

wp_get_canonical_url( int|WP_Post $post = null ) #

Returns the canonical URL for a post.


Description

When the post is the same as the current requested page the function will handle the pagination arguments too.


Top ↑

Parameters

$post

(int|WP_Post)(Optional) Post ID or object. Default is global $post.

Default value: null


Top ↑

Return

(string|false) The canonical URL, or false if the post does not exist or has not been published yet.


Top ↑

Source

File: wp-includes/link-template.php

3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
function wp_get_canonical_url( $post = null ) {
    $post = get_post( $post );
 
    if ( ! $post ) {
        return false;
    }
 
    if ( 'publish' !== $post->post_status ) {
        return false;
    }
 
    $canonical_url = get_permalink( $post );
 
    // If a canonical is being generated for the current page, make sure it has pagination if needed.
    if ( get_queried_object_id() === $post->ID ) {
        $page = get_query_var( 'page', 0 );
        if ( $page >= 2 ) {
            if ( ! get_option( 'permalink_structure' ) ) {
                $canonical_url = add_query_arg( 'page', $page, $canonical_url );
            } else {
                $canonical_url = trailingslashit( $canonical_url ) . user_trailingslashit( $page, 'single_paged' );
            }
        }
 
        $cpage = get_query_var( 'cpage', 0 );
        if ( $cpage ) {
            $canonical_url = get_comments_pagenum_link( $cpage );
        }
    }
 
    /**
     * Filters the canonical URL for a post.
     *
     * @since 4.6.0
     *
     * @param string  $canonical_url The post's canonical URL.
     * @param WP_Post $post          Post object.
     */
    return apply_filters( 'get_canonical_url', $canonical_url, $post );
}


Top ↑

Changelog

Changelog
VersionDescription
4.6.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by the Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More