skip to Main Content

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


  1. Chosen as BEST ANSWER

    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!


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search