get_post_permalink

Retrieves the permalink for a post of a custom post type.

Description

(string|WP_Error) get_post_permalink( (int) $id = 0, (constant) $leavename = false, (bool) $sample = false ); 

Returns (string|WP_Error)

The post permalink.

Parameters (3)

0. $id — Optional. (int)
Post ID. Default uses the global $post..
1. $leavename — Optional. (constant) => false
Optional, defaults to false. Whether to keep post name. Default false.
2. $sample — Optional. (bool) => false
Optional, defaults to false. Is it a sample permalink. Default false.

Usage

  1. if ( !function_exists( 'get_post_permalink' ) ) { 
  2. require_once ABSPATH . WPINC . '/link-template.php'; 
  3.  
  4. // Optional. Post ID. Default uses the global `$post`. 
  5. $id = -1; 
  6.  
  7. // Optional, defaults to false. Whether to keep post name. Default false. 
  8. $leavename = false; 
  9.  
  10. // Optional, defaults to false. Is it a sample permalink. Default false. 
  11. $sample = false; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = get_post_permalink($id, $leavename, $sample); 
  15.  

Defined (1)

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

/wp-includes/link-template.php  
  1. function get_post_permalink( $id = 0, $leavename = false, $sample = false ) { 
  2. global $wp_rewrite; 
  3.  
  4. $post = get_post($id); 
  5.  
  6. if ( is_wp_error( $post ) ) 
  7. return $post; 
  8.  
  9. $post_link = $wp_rewrite->get_extra_permastruct($post->post_type); 
  10.  
  11. $slug = $post->post_name; 
  12.  
  13. $draft_or_pending = get_post_status( $id ) && in_array( get_post_status( $id ), array( 'draft', 'pending', 'auto-draft', 'future' ) ); 
  14.  
  15. $post_type = get_post_type_object($post->post_type); 
  16.  
  17. if ( $post_type->hierarchical ) { 
  18. $slug = get_page_uri( $id ); 
  19.  
  20. if ( !empty($post_link) && ( !$draft_or_pending || $sample ) ) { 
  21. if ( ! $leavename ) { 
  22. $post_link = str_replace("%$post->post_type%", $slug, $post_link); 
  23. $post_link = home_url( user_trailingslashit($post_link) ); 
  24. } else { 
  25. if ( $post_type->query_var && ( isset($post->post_status) && !$draft_or_pending ) ) 
  26. $post_link = add_query_arg($post_type->query_var, $slug, ''); 
  27. else 
  28. $post_link = add_query_arg(array('post_type' => $post->post_type, 'p' => $post->ID), ''); 
  29. $post_link = home_url($post_link); 
  30.  
  31. /** 
  32. * Filters the permalink for a post of a custom post type. 
  33. * @since 3.0.0 
  34. * @param string $post_link The post's permalink. 
  35. * @param WP_Post $post The post in question. 
  36. * @param bool $leavename Whether to keep the post name. 
  37. * @param bool $sample Is it a sample permalink. 
  38. */ 
  39. return apply_filters( 'post_type_link', $post_link, $post, $leavename, $sample );