I'm trying to set a custom taxonomy term to some of my custom posts using the following code:
function gmpa_set_default_object_terms( $post_id, $post ) {
if ( 'publish' === $post->post_status && $post->post_type === 'team-members' ) {
$defaults = array(
'team-category' => array( 'all' )
//'your_taxonomy_id' => array( 'your_term_slug', 'your_term_slug' )
);
$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', 'gmpa_set_default_object_terms', 100, 2 );
It was working originally when I saved each post, but now it's not applying the default tax term when I resave. Is there a better way to do this with the Types plugin, or can you see why it's not working? Thanks!
Dear dave,
I assume we are talking about this case:
Custom post type "team-members" + custom taxonomy "team-category" + term "all"
I just tested it in my localhost with fresh wordpress installation + Types 2.2.1, it works fine.
I suggest you check these in your own website:
1) deactivate other plugins and switch to wordpress default theme, and test again
2) Make sure the post is in the "Published" status, since there is a condition in your PHP codes:
if ( 'publish' === $post->post_status ...
And I don't think there other better way within Types plugin.
Thanks, I ended up not needing the default tax applied to these custom posts. Thanks for your help!