wp_get_canonical_url

Advertisement

Summery Summery

Returns the canonical URL for a post.

Syntax Syntax

wp_get_canonical_url( int|WP_Post $post = null )

Description Description

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

Parameters Parameters

$post

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

Default value: null

Return Return

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

Source Source

File: wp-includes/link-template.php

	 *
	 * @param string $url     The complete URL including scheme and path.
	 * @param int    $user_id The user ID.
	 * @param string $scheme  Scheme to give the URL context. Accepts 'http', 'https', 'login',
	 *                        'login_post', 'admin', 'relative' or null.
	 */
	return apply_filters( 'edit_profile_url', $url, $user_id, $scheme );
}

/**
 * Returns the canonical URL for a post.
 *
 * When the post is the same as the current requested page the function will handle the
 * pagination arguments too.
 *
 * @since 4.6.0
 *
 * @param int|WP_Post $post Optional. Post ID or object. Default is global `$post`.
 * @return string|false The canonical URL, or false if the post does not exist or has not
 *                      been published yet.
 */
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 );

Advertisement

Changelog Changelog

Changelog
Version Description
4.6.0 Introduced.

Advertisement

Leave a Reply