In my plugin, I have a custom post type with a specific behaviour.
The administrator after to publish it, he should not be able to set the post as draft again.
How can I do this ?
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityIn my plugin, I have a custom post type with a specific behaviour.
The administrator after to publish it, he should not be able to set the post as draft again.
How can I do this ?
I would recommend the transition_post_status
hook, which allows you to hook into when a post is transitioning (or anytime a post is saved). In the example below, we check if the post is apart of your custom post type. Then we see if the old status was published and if the new status is not published, we throw an error.
<?php
add_action( 'transition_post_status', 'tps_no_draft_after_publish', 10, 3 );
function tps_no_draft_after_publish( $new_status, $old_status, $post ) {
if ( ( 'publish' !== $new_status && 'publish' === $old_status ) && 'my-custom-post-type' === $post->post_type
) {
wp_die('Posts that have been published cannot be set as draft.');
}
}
Additional reading:
I was looking for a solution to display the submit box wihtout draft button.
The code to display this box is generated by the function post_submit_meta_box
from wp-admin/includes/meta-boxes.php
.
As we can see, there is no hook to overwrite some code, so this following solution step by step is the best way I found without using a dirty solution like hide with css or js :
public function remove_customized_metabox(){
remove_meta_box( 'submitdiv', $post_type_slug, 'side' );
}
add_action( 'add_meta_boxes', "remove_customized_metabox", 10 );
You must use a different id than
submitdiv
to show your metabox
In my case I prefixed with underscore :_submitdiv
add_meta_box(
"_submitdiv",
__( "Publish" ),
"my_custom_callback",
$post_type_slug,
'side',
'core',
[ 'show_draft_button' => false ]
);
Based on post_submit_meta_box
, write your callback function like this :
public function my_custom_callback(?\WP_Post $post, array $callback_args){
global $action;
$post_type = $post->post_type;
$post_type_object = get_post_type_object($post_type);
$can_publish = current_user_can($post_type_object->cap->publish_posts);
?>
<div class="submitbox" id="submitpost">
...
if( $callback_args['show_draft_button'] ) {
//display the draft button
}
...
}
_submitdiv
by submitdiv
with jqueryif you want to change the publish date,
post.js
use the anchor#submitdiv
so you must change the id.
wp_enqueue_style( "metaboxsubmitstyle", "path/css/admin-metabox-submit.css" );
wp_enqueue_script( "metaboxsubmitscript", "path/js/admin-metabox-submit.js" );
#poststuff #_submitdiv .inside {
margin: 0;
padding: 0;
}
jQuery(function ($) {
$(document).ready(function () {
$("#_submitdiv").attr( 'id', "submitdiv");
});
});