Search code examples
wordpresswordpress-rest-api

Can I turn a WordPress Draft into a published post with a direct link if I know the post ID?


For example, using a function like this:

http://website.com/wp-admin/post.php?post=%%post_id%%&action=publish

P.S. I checked and this does not work, but I'm wondering if there is something similar in spirit that works?


Solution

  • You can paste this code in your theme functions.php file. This will do the trick, now if you change action parameter to draft and sent a get request , it will make that post draft.

    add_action( 'admin_init', 'draft_post_status_221' );
    function draft_post_status_221(){
    
        // Get current page , so this action will only fire in post.php page.
        global $pagenow;
    
        if ( $pagenow != 'post.php' ){
            return;
        }
    
        $post_id    = false;
        $action     = false;
    
        // get post id
        if ( isset($_GET['post']) && !empty($_GET['post']) ){
            $post_id = $_GET['post'];
        }
    
        // get action
        if ( isset($_GET['action']) && !empty($_GET['action']) ){
            $action = $_GET['action'];
    
            // for security we only allow draft action
            if ( $action != 'draft' ){
                $action = false;
            }
        }
    
        // if $post_id and $action has data than post will be updated.
        if ( !empty($post_id) && !empty($action) ){
    
            $args = array(
                'ID'            =>  $post_id,
                'post_status'   =>  $action
            );
    
            wp_update_post( $args );
        }
    
    }