How to create preview link of draft post with slug


In WordPress, the Draft post preview will have the below link:

But I want to custom this link to slug/permalink like: (This link have only category slug and post slug, it’s the same with published post link).

I am using post_link hook and use a trick to custom preview link: make the post status publish and switch to draft immediately. When I do that, the post will create the slug (post_name in the Database).

My code below:

add_filter('post_link', 'getDraftPermalink', 10, 2);

function getDraftPermalink($url, $post)
    $permalink = $url;
    remove_filter('post_link', [$this, 'getDraftPermalink'], 10);
    if ($post->post_status === 'draft') {
        $current_status = $post->post_status;
        $post->post_status = 'published';
        $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
        $permalink = get_permalink($post);
        $post->post_status = $current_status;

    add_filter('post_link', [$this, 'getDraftPermalink'], 10, 2);

    return $permalink;

Result: It’s work but it cause some bugs like:

  • Can not click publish button to publish the post, can not move to trash, …
    because the hook post_link will be run in many screens, files and requests (I think that).

I want to filter that:

  • My callback hook (getDraftPermalink) or the code inside the if statement will only run when I click in "Preview" button.
  • Otherwise, It must not run.
    Or suggest me to use others hooks because I am a newbie of WP development.

Thank you so much.

NhatThanh 3 months 0 Answers 9 views 0

Leave an answer