How to create preview link of draft post with slug

Question

In WordPress, the Draft post preview will have the below link: mysite.com/?p=2000&preview=true

But I want to custom this link to slug/permalink like: mysite.com/my-category/my-post-slug?preview=true (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';
        wp_update_post($post);
        $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;
        wp_update_post($post);
    }

    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.

0
NhatThanh 3 months 0 Answers 9 views 0

Leave an answer