I’d like to add one category automatically to a post when I hit “published” , perhaps by creating a function to put in functions.php ? This will save me time instead of scrolling through a ton of categories to tick off. For example, assign the category “awesome” to all posts (while retaining the categories that each post already has been assigned).
Brainstorm Method A
Is it possible accomplish this by making a function out of wp_set_post_categories
or wp_set_object_terms
for the category called “awesome” ? I do not understand the codex enough to customize it to fit my needs.
<?php wp_set_post_categories( $post_ID, $post_categories, $append ) ?>
or
<?php wp_set_object_terms( $object_id, $terms, $taxonomy, $append ); ?>
Brainstorm Method B
Also, I stumbled on this code below but do not know how to use it. Will the below code work for me? If yes, how would you customize this code for a category called “awesome” ? And are there places in the code that I need to replace with my information ? Or would you suggest using the above codes instead ? Or another method ?
“CODE A”: Automatically categorize and tag posts when saved ( taken from wpsnipp.com )
<?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 );
}
?>
I’d just go the easy route and do it with jQuery. Put the ID of the desired category in the selector (
#in-category-7
in this example):To do it with hooks and all that, research for
save_post
+wp_insert_term
. In those search results I haven’t found an example of refinedsave_post
(and it needs to be). Search only forsave_post
for good examples.