Inserting Category programmatically

Keep track of the return value of wp_insert_term and use it to build your structure. A successful return value will be an array with a term_id key that you can pass into wp_insert_term‘s $args array as parent. $parent = wp_insert_term(‘Science’, ‘category’); // I’ll leave out `$args` here if (is_wp_error($parent)) { // insert didn’t work! return … Read more

Group child category IDs based on their parent category

The quick take would be something like this: $categories = [ ]; $parent_categories = get_categories( [ ‘parent’ => 0 ] ); foreach ( $parent_categories as $parent_category ) { $id = $parent_category->term_id; $categories[ $id ] = wp_list_pluck( get_categories( [ ‘parent’ => $id ] ), ‘term_id’ ); } The important bit is a parent argument, which limits … Read more

Insert terms for custom taxonomy on plugin activation, or each page load (init hook)

50 is relatively not much, and you should create them on the plugin activation hook. For more then 100 (just pulled the number out of my ass 😉 do your own testing on some slow shared hosting) I would create a settings page and initialize the DB from there. The reason is that users do … Read more

Insert term when page is published – avoid duplicates after edits

I suggest post status transitions that runs only when your set conditions are met. Example: add_action( ‘transition_post_status’, ‘add_awesome_terms’, 10, 3 ); function add_awesome_terms( $new_status, $old_status, $post ) { // only run when it’s a page, new status is publish and old status isn’t publish if ( $post->post_type == ‘page’ && $new_status == ‘publish’ && $old_status … Read more

Question with get_the_term_list

You could use get_terms() and loop through it – using the term description as the “short name” and slug as the specific class ( or you could use an array of colors of your choice ). Let’s look at a quick example: <?php $terms = wp_get_post_terms( $post_id, ‘category’ ); if( ! empty( $terms ) ) … Read more

List child terms if parent but show nothing on children

For reliability, you can get the current term being viewed from the queried object from $GLOBALS[‘wp_the_query’] $current_term = sanitize_term( $GLOBALS[‘wp_the_query’]->get_queried_object() ); To answer your question, if Southern Africa is top level, it should have a parent term ID of 0. All child terms should have a numeric value as parent which corresponds to the parent … Read more