0

Can someone tell me what's wrong here? I'm trying to create a category and a sub-category via PHP.

My code is

wp_set_object_terms($postID, array($subCategory, $catgeory), 'category');

But that creates two categories on the same hirearchy level; my goal is a category with a sub-category.

3

You can use the wp_insert_term() function to achive this. First create the parent category, then create a child category.

$parent = wp_insert_term(
    'Parent Category', // category name
    'category', // taxonomy
    array(
        'description' => 'Category description', // optional
        'slug' => 'parent-category', // optional
    )
);

wp_insert_term(
    'Child Category', // category name
    'category', // taxonomy
    array(
        'description' => 'Child category description', // optional
        'slug' => 'child-category', // optional
        'parent' => $parent['term_id'], // set it as a sub-category
    )
);
  • Your answer had errors in it. One was syntax (no comma after slug => parent-category line) and for some reason $parent['temr_id'] didnt work despite it looking correct in the codex... But it DID lead me in the right direction and I eventually got it working, so thank you! My solution (theres probably an easier/simpler way): $parent = wp_set_object_terms($postID, $city, 'category'); $parentID = get_cat_id($parent);$child = wp_set_object_terms($postID, $eventType, 'category', array('slug' => $eventSlug, 'parent' => $parentID)); – user44440 Dec 29 '13 at 13:54
0

Your answer had errors in it. One was syntax (no comma after slug => parent-category line) and for some reason $parent['temr_id'] didnt work despite it looking correct in the codex...

But it DID lead me in the right direction and I eventually got it working, so thank you!

My solution (theres probably an easier/simpler way):

$parentTitle = 'category name';
$parentSlug = str_replace(' ', '', $parentTitle);
$parent = wp_set_object_terms($postID, $parentTitle, 'category', array('slug' => $parentSlug));
$parentID = get_cat_id($parent);
$childTitle = 'category name';
$childSlug = str_replace(' ', '', $childTitle);
$child = wp_set_object_terms($postID, $childTitle, 'category', array('slug' => $childSlug, 'parent' => $parentID));

Again, thanks for pointing me in the right direction!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.