Hi
I have this custom post type ( Cities ) which has been created with toolset. Now I'd like to automatically assign the default 'new' taxonomy term to this post type every time a new post is created ( hidden link ).
I have used this code but it doesn't work
/*
* Set default taxonomy term on custom post
*/
function tssupp_default_term( $post_id, $post, $update ){
// don't mess with existing posts
if ( !$update ) {
$default_term = '3'; // ID of the required term
$taxonomy = "new"; // slug of the taxonomy
wp_set_post_terms( $post_id, $default_term, $taxonomy );
}
}
add_action( 'save_post_city', 'tssupp_default_term', 101, 3 );
Let me know pls if you need access credentials to my site and the FTP account
Sincerely
Hi, the code looks pretty good at first glance. Is "new" a flat taxonomy or a hierarchical taxonomy? Flat taxonomy terms should be set using names, not IDs, according to the wp_set_post_terms documentation: https://codex.wordpress.org/Function_Reference/wp_set_post_terms
Oh and I just noticed that you're using the save_post_city hook. That hook isn't supported for post types registered by Toolset, and should not be used. An example showing how to apply a conditional per post type is available here:
https://toolset.com/documentation/customizing-sites-using-php/updating-types-fields-using-php/
It's a hierrarchical taxonomy ( hidden link )
I used this code now but i throws an error
function tssupp_default_terms( $post_id, $post, $update ){
if ( 'city' == $post->post_type) {
$default_term = '3'; // ID of the required term
$taxonomy = "new"; // slug of the taxonomy
wp_set_post_terms( $post_id, $default_term, $taxonomy );
}
}
add_action( 'save_post', 'tssupp_default_terms', 30, 2 );
Try updating the number of params to 3 instead of 2:
add_action( 'save_post', 'tssupp_default_terms', 30, 3 );
That's because there are 3 parameters here:
function tssupp_default_terms( $post_id, $post, $update ){
I'm not getting the error anymore but nothings happens
function tssupp_default_terms( $post_id, $post, $update ){
if ( 'city' == $post->post_type) {
$default_term = '3'; // ID of the required term
$taxonomy = "new"; // slug of the taxonomy
wp_set_post_terms( $post_id, $default_term, $taxonomy );
}
}
add_action( 'save_post', 'tssupp_default_terms', 30, 3 );
Don't I need to insert the "if ( !$update ) {" somewhere?
Regards
Don't I need to insert the "if ( !$update ) {" somewhere?
If you only want this code to be applied to new posts, yes. But if nothing is happening with the code now, adding the conditional won't fix anything. May I log in to see how this is set up?
The term slug is "new", but that's not what we're looking for in this code. The taxonomy slug is "city-type". See the attachment here. Please update $taxonomy to be "city-type" in your code and try again.
Awesome Help 🙂 My issue is resolved now. Thank you!