I am looking for a way to auto tag custom posts in WordPress without using a plugin.
I have a custom post type ‘tech-video
‘ and I want to auto tag it with the video
tag every time a post gets published of that type.
I tried this code snippet but it doesn’t work:
/* Auto Tag Tech Videos */
add_action('publish_tech_video', 'tag_tech_video', 10, 2);
function tag_tech_video($post_id, $post){
wp_set_post_terms( $post_id, 'tech-video', 'video', true );
}
I’m not skilled with either PHP or WordPress hooks so any help is appreciated.
Thank you,
2
Answers
After doing some more digging into the Wordpress Codex I was able to figure out a more elegant solution that works great:
Note that I had to change
tech_video
to 'tech-video
' to make it match the name defined by the Custom Post Type (and thus call properly).I like this method because it's cleaner.
Thanks @andrew for pointing me in the right direction at least!
You’re close; You just got the hook name wrong.
Whenever a post is saved, the following is run:
To leverage this hook you can run:
But note: Since the "save_post" hook is run every time the post is saved, you need to check that the term has not already been added.
Note that the signature for
wp_set_post_terms
is:So this assumes that you have a registered taxonomy named "video", and the taxonomy is linked to the "tech_video" post type.