3
votes

I am categorizing a custom posttype by a taxonomy (More Taxonomies) term for year. What I want is my custom post type to have the current year automatically selected as a default taxonomy term when I'm going to add a new post.

So, in pseudo code I would like the to set default taxonomy term for custom post type where term name is date("Y").

Any ideas how I can do this, and/or how to set default taxonomy term?

1

1 Answers

5
votes

You can use the following:

function prefix_post_year( $post_id ) {
    $current_post = get_post( $post_id );

    // This makes sure the taxonomy is only set when a new post is created
    if ( $current_post->post_date == $current_post->post_modified ) {
        wp_set_object_terms( $post_id, date( 'Y' ), {taxonomy}, true );
    }
}
add_action( 'save_post_{post_type}', 'prefix_post_year' );

Notes:

  • change {post_type} to your post type's name. So if your post type is "project", the action should be save_post_project
  • similarly change {taxonomy} to your taxonomy's name, for example wp_set_object_terms( $post_id, date( 'Y' ), 'project-year', true );
  • if your taxonomy term is something like "project-posted-in-2015", change date( 'Y' ) to 'project-posted-in-' . date( 'Y' )