views:

21

answers:

1

I have several categories in which I need to update/assign the parent category so that the default category (uncategorized) becomes the parent.

Its very easy to do this via the category manager, however, I need to do this via script.

+1  A: 

The original source code for wp_update_cagetory() is:

/**
 * Aliases wp_insert_category() with minimal args.
 *
* If you want to update only some fields of an existing category, call this
* function with only the new values set inside $catarr.
*
* @since 2.0.0
*
* @param array $catarr The 'cat_ID' value is required.  All other keys are optional.
* @return int|bool The ID number of the new or updated Category on success. Zero or FALSE on failure.
 */
function wp_update_category($catarr) {
    $cat_ID = (int) $catarr['cat_ID'];

    if ( isset($catarr['category_parent']) && ($cat_ID == $catarr['category_parent']) )
        return false;

// First, get all of the original fields
$category = get_category($cat_ID, ARRAY_A);

// Escape data pulled from DB.
$category = add_magic_quotes($category);

// Merge old and new fields with new fields overwriting old ones.
$catarr = array_merge($category, $catarr);

return wp_insert_category($catarr);
}

So this seems self-explanatory:

$modifiedCategory = array();

$modifiedCategory['cat_ID'] = 12; // This should be your modified category ID
$modifiedCategory['category_parent'] = 1; // This should be your desired parent category (in my case 1 == Uncategorized)

wp_update_category($modifiedCategory);

Repeat the above for all categories you need updated.

UPDATE:

Pertaining to the problem of category ID retrieval - it seems that category_exists() function should do the job:

function category_exists($cat_name, $parent = 0) {
$id = is_term($cat_name, 'category', $parent);
if ( is_array($id) )
    $id = $id['term_id'];
return $id;
}

So this should work, but I didn't test it:

$modifiedCategory['cat_ID'] = category_exists('some category');
$modifiedCategory['category_parent'] = category_exists('Uncategorized');
Karol Piczak
Thanks Karol, I want necessarily know the category ids of each installation (this is deployed code on multiple sites). Do you have an example of setting the category_parent of a category using the category_name or slug?
Scott B
See if the updated answer solves your problem. I'm not certain if it works, but looking at WordPress code it seems OK.
Karol Piczak