Home > Back-end >  Auto tag custom posts in Wordpress
Auto tag custom posts in Wordpress

Time:09-08

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,

CodePudding user response:

You're close; You just got the hook name wrong.

Whenever a post is saved, the following is run:

do_action( "save_post_{$post->post_type}", $post->ID, $post, true );

To leverage this hook you can run:

add_action('save_post_tech_video', 'tag_tech_video', 10, 2);
function tag_tech_video($post_id, $post){
    // check the term has not already been added.
    $terms = wp_get_post_terms($post->ID, 'video');
    $term_names = array_map(function($term){return $term->name;},$terms);
    if(!in_array('tech-video',$term_names){
      wp_set_post_terms( $post_id, 'tech-video', 'video', true );
    }
}

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:

function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false );

So this assumes that you have a registered taxonomy named "video", and the taxonomy is linked to the "tech_video" post type.

CodePudding user response:

After doing some more digging into the Wordpress Codex I was able to figure out a more elegant solution that works great:

// Call when the post gets created
add_action('save_post_tech-video', 'tag_tech_video', 10, 2);

function tag_tech_video($post_id, $post) {
    // If the video tag doesn't exist, add it
    if (!has_tag('video', $post->ID)) {
      wp_set_post_tags( $post_id, 'video', true );
    }
}

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!

  • Related