Code Element At

Add WordPress Categories and Tags Programmatically

There are some instances where you might want to add default WordPress Categories and Tags programmatically. You can use the init action hook in conjunction with wp_update_term / term_exisits / wp_insert_term functions to accomplish this.

Replace:

‘category’: with the name of the custom taxonomy you would like to add default terms to, or use post_tag to add WordPress tags

/**
 * Add default post categories
 */
add_action('init', function () {

    // Update the default category 'uncategorized'
	wp_update_term(
        1,
		'category',
		array(
          'name'        => 'Category Name',
		  'description'	=> 'Some description',
		  'slug' 		=> 'category-slug'
		)
    );

    // Check if new category exists - if not, add it
    if (!term_exists('new-category-slug', 'category')) {
		wp_insert_term(
			'New Category Name',
			'category',
			array(
				'description' => 'Some description',
				'slug'		  => 'new-category-slug'
			)
		);
    }
    
    // If you have many terms to add use an array
    $days_of_week = array('sunday' => 'Sun', 'monday' => 'Mon', 'tuesday' => 'Tue', 'wednesday' => 'Wed', 'thursday' => 'Thurs', 'friday' => 'Fri', 'saturday' => 'Sat');
    foreach ( $days_of_week as $slug => $name ) {
        if( !term_exists( $name, 'category' ) ) {
            wp_insert_term(
                $name,
                'category',
                array(
			  		'description' => '',
                	'slug'        => $slug
                )
            );
        }
    }
});