The post_permalink() WordPress PHP function retrieves the permalink from a post ID or a WP_Post object.
Usage
To use the function, simply call post_permalink($post_id) where $post_id is the ID of the post you want the permalink for. The function will return the permalink as a string.
Parameters
$post (int|WP_Post): Optional. Post ID or WP_Post object. Default is global$post.
More information
See WordPress Developer Resources: post_permalink
Examples
Retrieve Permalink Using Post ID
This example demonstrates how to retrieve the permalink of a post using its ID.
$post_id = 123; $permalink = post_permalink($post_id); echo "The permalink for post $post_id is: $permalink";
Retrieve Permalink Using WP_Post Object
This example shows how to retrieve the permalink of a post using a WP_Post object.
$post_object = get_post(123);
$permalink = post_permalink($post_object);
echo "The permalink for post {$post_object->ID} is: $permalink";
Display Permalink in a Template
This example demonstrates how to display the permalink of a post within a WordPress template.
while (have_posts()) {
the_post();
echo 'Post title: ' . get_the_title() . '<br>';
echo 'Permalink: ' . post_permalink() . '<br><br>';
}
Create an HTML Link with the Permalink
This example shows how to create an HTML link using the post permalink.
$post_id = 123; $permalink = post_permalink($post_id); echo "<a href='$permalink'>Read more about this post</a>";
Retrieve Permalink for All Posts in a Category
This example demonstrates how to retrieve permalinks for all posts in a specific category.
$category_id = 5;
$args = array(
'category' => $category_id,
'posts_per_page' => -1
);
$posts = get_posts($args);
foreach ($posts as $post) {
echo 'Post title: ' . $post->post_title . '<br>';
echo 'Permalink: ' . post_permalink($post->ID) . '<br><br>';
}