I have a CPT - 'Events' with 400+ posts [with no terms in the custom taxonomy (tax_category) selected] in them, as I recently imported those posts.

Now, I've created a URL structure where I need to have some term of tax_category assigned to each post. So, is there any way with which I can assign a term from tax_category (say 'New Gigs') to all posts of the Events cpt?

While searching I also found the following code, but am confused of how can I modify it suit my need or it even is the solution am looking for? -

function mfields_set_default_object_terms( $post_id, $post ) {
    if ( 'publish' === $post->post_status ) {
        $defaults = array(
            'post_tag' => array( 'taco', 'banana' ),
            'monkey-faces' => array( 'see-no-evil' ),
        $taxonomies = get_object_taxonomies( $post->post_type );
        foreach ( (array) $taxonomies as $taxonomy ) {
            $terms = wp_get_post_terms( $post_id, $taxonomy );
            if ( empty( $terms ) && array_key_exists( $taxonomy, $defaults ) ) {
                wp_set_object_terms( $post_id, $defaults[$taxonomy], $taxonomy );
add_action( 'save_post', 'mfields_set_default_object_terms', 100, 2 ); 

Code Source - http://wordpress.mfields.org/2010/set-default-terms-for-your-custom-taxonomies-in-wordpress-3-0/


Try this:

function custom_set_term_to_post(){
    $args = array(
        'post_type' => 'post',
    $all_posts = get_posts();
    foreach ($all_posts as $key => $post) {
        $tag_name = 'post_tag'; // required tag name
        $term_list = wp_get_post_terms($post->ID, $tag_name, array("fields" => "ids"));
        if (!empty($term_list)) {
            // there is already tags; need not do anything
        $tag = array( 23 ); // required tag ID to assign
        wp_set_post_terms( $post->ID, $tag, $tag_name );

This function scans all posts of post type post and check if it has any tag or not. If no any tag is assigned, then required tag is assigned. Here tag name is post_tag. And required tag item is of id 23. Replace it with your value. Make sure this function only run once. Just for current purpose. Dont leave it in the theme. :-)

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.