wp_get_canonical_url

Returns the canonical URL for a post.

Description

(string|false) wp_get_canonical_url( (null) $post = null ); 

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

Returns (string|false)

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

Parameters (1)

0. $post — Optional. (null) => null
Post ID or object. Default is global $post..

Usage

  1. if ( !function_exists( 'wp_get_canonical_url' ) ) { 
  2. require_once ABSPATH . WPINC . '/link-template.php'; 
  3.  
  4. // Optional. Post ID or object. Default is global `$post`. 
  5. $post = null; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wp_get_canonical_url($post); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/link-template.php  
  1. function wp_get_canonical_url( $post = null ) { 
  2. $post = get_post( $post ); 
  3.  
  4. if ( ! $post ) { 
  5. return false; 
  6.  
  7. if ( 'publish' !== $post->post_status ) { 
  8. return false; 
  9.  
  10. $canonical_url = get_permalink( $post ); 
  11.  
  12. // If a canonical is being generated for the current page, make sure it has pagination if needed. 
  13. if ( $post->ID === get_queried_object_id() ) { 
  14. $page = get_query_var( 'page', 0 ); 
  15. if ( $page >= 2 ) { 
  16. if ( '' == get_option( 'permalink_structure' ) ) { 
  17. $canonical_url = add_query_arg( 'page', $page, $canonical_url ); 
  18. } else { 
  19. $canonical_url = trailingslashit( $canonical_url ) . user_trailingslashit( $page, 'single_paged' ); 
  20.  
  21. $cpage = get_query_var( 'cpage', 0 ); 
  22. if ( $cpage ) { 
  23. $canonical_url = get_comments_pagenum_link( $cpage ); 
  24.  
  25. /** 
  26. * Filters the canonical URL for a post. 
  27. * @since 4.6.0 
  28. * @param string $string The post's canonical URL. 
  29. * @param WP_Post $post Post object. 
  30. */ 
  31. return apply_filters( 'get_canonical_url', $canonical_url, $post );