Using WordPress ‘get_post_permalink()’ PHP function

The get_post_permalink() WordPress PHP function retrieves the permalink for a post of a custom post type.

Usage

get_post_permalink($post, $leavename, $sample);

Example:

Input:

$post_id = 123;
$permalink = get_post_permalink($post_id);
echo $permalink;

Output:

https://example.com/custom-post-type/123-custom-post-name/

Parameters

  • $post (int|WP_Post, Optional): Post ID or post object. Default is the global $post.
  • $leavename (bool, Optional): Whether to keep the post name. Default is false.
  • $sample (bool, Optional): Is it a sample permalink. Default is false.

More information

See WordPress Developer Resources: get_post_permalink()

Examples

Display permalink of the current post

This example retrieves the permalink of the current post and displays it.

$current_permalink = get_post_permalink();
echo "Current post permalink: " . $current_permalink;

Display permalink of a specific post

This example retrieves the permalink of a specific post with a given ID and displays it.

$post_id = 123;
$specific_permalink = get_post_permalink($post_id);
echo "Permalink for post with ID 123: " . $specific_permalink;

Display permalink without post name

This example retrieves the permalink of a specific post without the post name and displays it.

$post_id = 123;
$permalink_without_name = get_post_permalink($post_id, true);
echo "Permalink without post name: " . $permalink_without_name;

This example retrieves a sample permalink of a specific post and displays it.

$post_id = 123;
$sample_permalink = get_post_permalink($post_id, false, true);
echo "Sample permalink: " . $sample_permalink;

Display permalink of a WP_Post object

This example retrieves the permalink of a specific WP_Post object and displays it.

$post = get_post(123);
$post_permalink = get_post_permalink($post);
echo "Permalink for WP_Post object: " . $post_permalink;