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).
How could I use this to simply add specific tags to a product?
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