I have a custom post type called "shift" (as in shifts worked by employees). When shifts are published, I run an Ajax function to check that this shift does not have a scheduling conflict. If there is a scheduling conflict, a dialog box pops up alerting the user of the conflict and asking if they want to continue. If they choose "cancel", the post isn't published. If they choose "continue", the post is published.
Here's the problem: if they choose "continue", the post gets saved as a draft instead of being published. How can I make the post be published when they click the "publish" button?
Here is the JS (simplified a bit so you can see the important parts):
$('#publish').on('click', function (e) {
e.preventDefault();
var url = shiftajax.ajaxurl;
var shift = $('#post_ID').val();
var data = {
'action': 'wpaesm_check_for_schedule_conflicts_before_publish',
'shift': shift,
};
$.post(url, data, function (response) {
if( response.action == 'go' ) {
// there aren't any scheduling conflicts, so we can publish the post
$('#hidden_post_status').val('publish');
$('#post').submit();
} else {
// there are scheduling conflicts, so ask the user if they want to publish
if (confirm(response.message)) {
$('#hidden_post_status').val('publish');
$('#post').submit();
} else {
// do nothing
}
}
});
});
Note the line $('#hidden_post_status').val('publish');
- that does change the value of the hidden field with an ID of "hidden_post_status", but that doesn't have an effect. The post is still saved as a draft.
wp_insert_post()
default post status isdraft
.$('#post').submit();
in the JS is what publishes the post.