Farooq Ahmad Farooq Ahmad - 4 months ago 39
PHP Question

Create Category and sub Category Programmatically

This code show properly category in wordpress admin area. but not showing subcategory.

Need to show 3 categories and 3 subcategories for each??

My question is like this:

Category A


  • sub-category 1

  • sub-category 2

  • sub-category 3



I create the following in wordpress theme's functions.php:

//create the main category
wp_insert_term(

// the name of the category
'Category A',

// the taxonomy, which in this case if category (don't change)
'category',

array(

// what to use in the url for term archive
'slug' => 'category-a',
));`


Then for each sub-category

wp_insert_term(

// the name of the sub-category
'Sub-category 1',

// the taxonomy 'category' (don't change)
'category',

array(
// what to use in the url for term archive
'slug' => 'sub-cat-1',

// link with main category. In the case, become a child of the "Category A" parent
'parent'=> term_exists( 'Category A', 'category' )['term_id']

));

Answer

The problem is that you need to get the parent term id outside the function, to avoid the error. You can easily do it this way:

$parent_term_a = term_exists( 'Category A', 'category' ); // array is returned if taxonomy is given
$parent_term_a_id = $parent_term_a['term_id']; // get numeric term id
wp_insert_term(
    'Sub-category 1', // the term 
    'category', // the taxonomy
    array(
        // 'description'=> 'Some description.',
        'slug' => 'sub-cat-1a',
        'parent'=> $parent_term_a_id
    )
);

wp_insert_term(
    'Sub-category 2', // the term 
    'category', // the taxonomy
    array(
        // 'description'=> 'Some description.',
        'slug' => 'sub-cat-2a',
        'parent'=> $parent_term_a_id
    )
);

wp_insert_term(
    'Sub-category 3', // the term 
    'category', // the taxonomy
    array(
        // 'description'=> 'Some description.',
        'slug' => 'sub-cat-3a',
        'parent'=> $parent_term_a_id
    )
);

Then you will use for other 2 groups of subcategories:

$parent_term_b = term_exists( 'Category B', 'category' );
$parent_term_b_id = $parent_term_b['term_id'];

$parent_term_c = term_exists( 'Category C', 'category' );
$parent_term_c_id = $parent_term_c['term_id'];

… In the same way…

Reference:

Comments