I am trying to create a function that will set the default category to a post upon submit before it is published, but upon submission of the post, in the case that contributor doesn't set any category for the post. After the default category is added in the first submit, admin can review the post makes changes and even change the categories to his wish.

I have been searching and found many ideas and snippets but none to do what i am looking for and i am not so good with php :(

I have been trying with snippets from here and also i found that i can access the default category ID via default_category option:

$default_category = get_option('default_category');

So here is my idea:

function add_comm_category_automatically($post_id) {
global $wpdb;
if(!wp_is_post_revision($post_id)) {
$default_category = get_option('default_category');
wp_set_object_terms( $post_id, $default_category->term_id, 'category');
add_action('save_post', 'add_comm_category_automatically');

But this doesn't give me the default category that i have set in default post category under Settings -> Writing because i do some mistake, but just returns the ID of the default category .

And also this sinppets doesn't let admin edit or change categories (even remove the default category) upon publish or any other change. It just overrides all other categories that admin might want to replace this with.

So basicly i am trying to find a hook that will fire only upon the creation of the post just for one time and add the default category to the post if none was selected.

Any ideas would be highly appreciated.


I managed to set a code but i have noticed that it creates mistakes in the results some times.

What should be the requirments for a contributor and admin role:

  • setting a default category upon submit when there is no category selected ,
  • setting a default category upon draft or autodraft when there is no category selected ,

  • in general when there is no category selected, default category should be set.

  • if any role makes an changes in the categories, new categories should apply.

  • setting the default category if after any changes (draft or pending) there is no category selected.

The code that i made:

function save_post_callback( $post_id, $post, $update ) {
global $wpdb;
if ( $update || $post->post_status == "auto-draft" ) {

  if(!wp_is_post_revision($post_id)) {
$uncategorized= array (148); // Lets say that the default category has ID 148. How to get the default category?
wp_set_object_terms( $post_id, $uncategorized, 'category');

add_action( 'save_post', 'save_post_callback', 10, 3 );

I have been trying to get ideas from this or this or this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.