X

How to Automatically Categorize and Tag Posts in WordPress

Snippets by IsItWP

Too lazy to choose categories and tags for your WordPress posts? Then, why not automatically categorize and tag posts without your manual input? We’ll show you how to do it with our snippet.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

<?php

add_action( 'wp_insert_post', 'update_post_terms' );

function 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 );
    $newcat    = get_term_by( 'name', 'Some Category', 'category' );

    array_push( $categories, $newcat->term_id );
    wp_set_post_categories( $post_id, $categories );
}
?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: Best WordPress Page Builders (Compared).

Comments   Leave a Reply

  1. How could I use this to simply add specific tags to a product?

  2. are all categories generated and assigned as soon as activated or does it takes time? and do we need to restart our server?

    and categories are assigned based on a similar title? will this method work if my title is the same with only an addition of a number?

    ex: title1 , title2, title3

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!