Add categories and tags automatically to every post

If you want to pre-add custom categories and tags to every post this function snippet will help you to do so. Make sure the tags and categories already exists because we pull the IDs by their names.

/**
 * Snippet Name: Add categories and tags automatically to every post
 * Snippet URL: https://www.wpcustoms.net/snippets/add-categories-tags-automatically-every-post/
 */
  function wpc_update_post_terms( $post_id ) {
    if ( $parent = wp_is_post_revision( $post_id ) )
        $post_id = $parent;
    $post = get_post( $post_id );
    if ( $post->post_type != 'post' )
        return;
    // add a tag
    wp_set_post_terms( $post_id, 'new tag', 'post_tag', true );
    // add a category
    $categories = wp_get_post_categories( $post_id );
    // make sure these category names already exists. They are not created automatically.
    $newcat    = get_term_by( 'Some Category', 'category' );
    array_push( $categories, $newcat->term_id );
    wp_set_post_categories( $post_id, $categories );
}
add_action( 'wp_insert_post', 'wpc_update_post_terms' ); 

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x