auto check a category when creating new post

Solutions on MaxInterview for auto check a category when creating new post by the best coders in the world

showing results for - "auto check a category when creating new post"
Maria
05 Jul 2016
1add_filter('wp_terms_checklist_args', 'WPSE_pre_select_categories', 10, 2);
2function WPSE_pre_select_categories($args, $post_id) {
3        $post = get_post($post_id);
4
5        // only pre select categories for new posts
6        if ($post->post_status !== 'auto-draft' || $post->post_type !== 'post')
7                return $args;
8
9        // select categories with ID 4 and 6
10        $select_categories = [4, 6];
11
12        // little hack so array_merge() works if default is NULL
13        if (empty($args['selected_cats'])) {
14                $args['selected_cats'] = [];
15        }
16
17        // array_merge() with numerical indices only appends
18        // so I use array_unique() to remove any duplicates
19        $args['selected_cats'] = array_unique(array_merge($args['selected_cats'], $select_categories));
20        return $args;
21}
22