Using WordPress ‘get_sample_permalink()’ PHP function

The get_sample_permalink() WordPress PHP function returns a sample permalink based on the post name.

Usage

get_sample_permalink($post, $title, $name);

Example: list($permalink, $postname) = get_sample_permalink(42, 'My Custom Title', 'custom-post-name');

Parameters

  • $post int|WP_Post: Required. Post ID or post object.
  • $title string|null: Optional. Title to override the post’s current title when generating the post name. Default: null
  • $name string|null: Optional. Name to override the post name. Default: null

More information

See WordPress Developer Resources: get_sample_permalink()

Examples

Get Sample Permalink for a Post ID

Retrieve the sample permalink for a post with the ID of 42.

list($permalink, $postname) = get_sample_permalink(42);
echo "Sample permalink: $permalink";

Override the post’s current title with a custom title when generating the sample permalink.

list($permalink, $postname) = get_sample_permalink(42, 'My Custom Title');
echo "Sample permalink with custom title: $permalink";

Override Post Name for Sample Permalink

Override the post name with a custom name when generating the sample permalink.

list($permalink, $postname) = get_sample_permalink(42, null, 'custom-post-name');
echo "Sample permalink with custom post name: $permalink";

Override Title and Post Name for Sample Permalink

Override both the post’s current title and post name with custom values when generating the sample permalink.

list($permalink, $postname) = get_sample_permalink(42, 'My Custom Title', 'custom-post-name');
echo "Sample permalink with custom title and post name: $permalink";

Display Sample Permalink in a Post Loop

Display the sample permalink for each post in a loop.

$query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 5));

while ($query->have_posts()) {
    $query->the_post();
    list($permalink, $postname) = get_sample_permalink(get_the_ID());
    echo "Sample permalink for " . get_the_title() . ": $permalink<br>";
}
wp_reset_postdata();