Set posts of a custom post type to be private by default?
Say I created a custom post type called ‘Private Posts’ ($post_type
= itsme_private_posts
) and want all posts under the custom post type to be set to ‘Private’ automatically when published i.e. by default. How do I do it?
Based on @brasofilo’s answer to a related question on StackOverflow, I tried this:
add_filter( 'wp_insert_post_data', 'itsme_cpt_private', '99', 2 );
function itsme_cpt_private( $data , $postarr ) {
if( $postarr['post_type'] == 'itsme_private_posts' ) {
$data['post_status'] = 'private';
}
return $data;
}
It doesn’t work i.e. it doesn’t do anything; everything’s the way it was before adding the function. It’s as though the function doesn’t exist or simply does nothing.
Then, based on this article titled, “Force custom post type to be private“, I tried this:
add_filter( 'wp_insert_post_data', 'itsme_cpt_private' );
function itsme_cpt_private( $post ) {
if( $post['post_type'] == 'itsme_private_posts' ) {
$post['post_status'] = 'private';
}
return $post;
}
It works, in that, when I publish or update a post it turns private. Good! But when I create a new post (‘Add New’) and leave without doing anything, it creates a ‘private’ (auto-)draft and saves it. Moreover I can’t even trash that thing!
Essentially I can’t figure out how to do it. So, how do I set posts of a custom post type to be private by default?
Leave an answer