Prevent publish status/date saved on transition_post_status hook

Question

I’m using the transition_post_status to prevent a custom post type from being published based on a post meta field. It doesn’t seem to work entirely, and that’s where I need some help.

Here is a simplified version of what I have:

add_action( 'transition_post_status', [ $this, 'intercept_adherence_publishing' ], 9, 3 );

function intercept_adherence_publishing( $new_status, $old_status, $post ) {
        $post_id = $post->ID;
        $adherence_status = $_POST['_adherence_status'];

        if ( ( $new_status === 'publish' ) && ( $post->post_type == 'protocol-adherence' ) && ( $adherence_status !== 'accepted' ) ) {
            error_out('Published post ' . $post_id . ' intercepted. Post remains unpublished due to adherence not being accepted');
            wp_die( '<b>Adherence Error: </b>Cannot publish adherence that is not accepted. Please save status in "Pending Review" instead of the publish button if the adherence is not accepted yet.', 'Adherence Publishing Error', [ 'back_link' => true ]);
        }
    }

What is supposed to happen when post meta is not “accepted”:

  • wp_die() displays the admin error with a link to return to the post
  • post remains in pending review state with the “Save as pending” option
  • publish date still shows as “Publish immediately” above the publish button

What is actually happening with this code:

  • wp_die() displays the admin error with a link to return to the post (which is happening and is good)
  • post status goes from “pending review” to “published” and “save as pending” button disappears. (not good)
  • publish button now has a date above it saved like “Publish on Jan 10, 2019 @ 14:46” instead of retaining it’s “Publish immediately” status (not good)

Is there another hook I should be using or some additional logic I’d have to write in this function so that the post truly remains unpublished? As in we keep the “pending review” status/option and prevent a date from being saved?

Thanks in advance!

0
RachieVee 4 months 0 Answers 12 views 0

Leave an answer