0

I'd like to associate new posts created under a custom post type to automatically be given a custom taxonomy term. As a heads up here are the parameters

Custom Post Type Name: business_ser_dir_ltg
Custom Taxonomy Name: secondary-listing-category
Term Name: Business Services
Term Slug: business-services

function bus_default_terms( $post_id, $post, $update ){
if ( 'business_ser_dir_ltg' == $post->post_type) {

$default_term = '5480'; // ID of the required term
$taxonomy = "business-services"; // slug of the taxonomy

wp_set_post_terms( $post_id, $default_term, $taxonomy );

}
}
add_action( 'save_post', 'bus_default_terms', 30, 3 );

This is the code I created, but when I create a new post it does not automatically assign the term Business Services to the newly created post.

1

2 Answers 2

0

First of all, the third param of wp_set_post_terms must be a taxonomy slug, in this case, it's secondary-listing-category.

Second, the term ID should be in numeric type instead of string. Read the explanation here: https://developer.wordpress.org/reference/functions/wp_set_post_terms/#user-contributed-notes

Therefore, the correct code should be

function bus_default_terms($post_id, $post, $update){
    if('business_ser_dir_ltg' == $post->post_type){
        
        $default_term = 5480; // ID of the required term
        $taxonomy     = "secondary-listing-category"; // slug of the taxonomy
        
        wp_set_post_terms($post_id, intval($default_term), $taxonomy);
        
    }
}
add_action('save_post', 'bus_default_terms', 30, 3);
1
  • This is getting closer. The problem with this it adds the term 5480 automatically to the post instead of Business Services. I've changed the 5480 to Business Services and now it is working. Commented Aug 15 at 15:09
0

Thank you @Dao for your answer. I was able to figure out the solution. The answer is below:

/*Set Default Taxonomy to Business Services*/
function bus_default_terms($post_id, $post, $update){
    if('business_ser_dir_ltg' == $post->post_type){
        
        $default_term = 'Business Services'; // Name of the required term
        $taxonomy     = "secondary-listing-category"; // slug of the taxonomy
        
        wp_set_post_terms($post_id, $default_term, $taxonomy);
        
    }
}
add_action('save_post', 'bus_default_terms', 30, 3);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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