This should do what you want:
add_filter('save_post', 'wpse_135377_protect_post');
function wpse_135377_protect_post($post_ID) {
if (in_array(
'protected_category',
wp_get_post_categories($post_ID, array('fields' => 'slugs'))
)) {
// we have to remove the function
// as it will be called by `wp_update_post` (=> infinite loop)
remove_filter('save_post', 'wpse_135377_protect_post');
wp_update_post(array(
'ID' => $post_ID,
'post_password' => '123123',
));
// now we add it again
add_filter('save_post', 'wpse_135377_protect_post');
}
} // function wpse_135377_protect_post
There were several problems in your code base:
- there is no post status
protected—password protected posts have the post statuspublishas well (and they have a password); - you should use the
save_postaction (as suggested in the below comment and the linked answer); - the
$postobject that is passed into the functions (save_postas well asdefault_content) is not a pointer (reference) so anything you do to the object stays within the function (unless you insert it into the db).
Happy protecting!