Skip to content

Instantly share code, notes, and snippets.

@crawford252
Created August 16, 2023 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crawford252/a55e200db939751462882e0e6a4cd4d5 to your computer and use it in GitHub Desktop.
Save crawford252/a55e200db939751462882e0e6a4cd4d5 to your computer and use it in GitHub Desktop.
function dp_assign_post_year_term($post_id, $post, $update) {
// Assign for new posts only
if($update) {
return;
}
// Assign only if post type is "post"
if ( 'post' !== $post->post_type ) {
return;
}
// Get the current year
$current_year = date('Y');
// Assign the post to the term in the "post_date" taxonomy with the current year
$current_year_term_id = dp_check_create_term( $current_year, $post_id);
if($current_year_term_id) {
// Get the current Month
$current_month = date('F');
// Assign the post to the term in the "post_date" taxonomy with the current month
$result = dp_check_create_term( $current_month, $post_id, $current_year_term_id, $current_year);
}
}
add_action('save_post', 'dp_assign_post_year_term', 10, 3);
function dp_check_create_term($value, $post_id, $parent_term_id = null, $current_year = null) {
$term = term_exists( $value, 'post_date', $parent_term_id);
if( $term ) {
// Term exists
$existing_term_array = wp_set_post_terms( $post_id, $term['term_id'], 'post_date', true );
if(!empty($existing_term_array) && is_array($existing_term_array)) {
return $existing_term_array[0];
}
} else {
// Create new term
$args = [];
if($parent_term_id) {
$args = array(
'parent' => $parent_term_id,
'slug' => $value.'-'.$current_year,
);
}
$new_term = wp_insert_term($value, 'post_date', $args);
if( $new_term ) {
$new_term_array = wp_set_post_terms( $post_id, $new_term['term_id'], 'post_date', true );
if(!empty($new_term_array) && is_array($new_term_array)) {
return $new_term_array[0];
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment