0
votes

I am creating two categories within my functions.php file when my Wordpress theme is activated like so:

/**
 * @desc Create categories on theme activation
 **/
function create_my_cat () {
if (file_exists (ABSPATH.'/wp-admin/includes/taxonomy.php')) {
    require_once (ABSPATH.'/wp-admin/includes/taxonomy.php'); 
    if ( ! get_cat_ID( 'Work' ) ) {
        wp_create_category( 'Work' );
    }
    if ( ! get_cat_ID( 'Blog' ) ) {
        wp_create_category( 'Blog' );
    }
}
}
add_action ( 'after_setup_theme', 'create_my_cat' );

If the two categories Work and Blog do not already exist, create them but if they do already exist, do nothing.

How do I get the ID's of those two new categories when they are created/if they already exist? I need to store them as two separate variables ($work & $blog) if possible so I can reuse them within the same file.

1

1 Answers

1
votes

From wordpress manual

wp_create_category( $cat_name, $parent ):
  • Returns 0 on failure, category id on success.
  • If the category already exists, it is not duplicated. The ID of the original existing category is returned without error.
$work = wp_create_category( 'Work' );
$blog = wp_create_category( 'Blog' );

I tested the behavior and works exactly as written in the instructions