Skip to content

Instantly share code, notes, and snippets.

@crawford252
Created August 16, 2023 12:23
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/d1ae601923bef9a7943f325227e6ad2b to your computer and use it in GitHub Desktop.
Save crawford252/d1ae601923bef9a7943f325227e6ad2b to your computer and use it in GitHub Desktop.
Loop through existing posts and add year and month terms based on publish date
/* ONLY RUN THIS FUNCTION ONE TIME */
function dp_set_publish_date_taxonomy_all_posts() {
$posts = get_posts(array(
'post_type' => 'post',
'posts_per_page' => -1,
));
foreach ($posts as $post) {
$post_id = $post->ID;
// Get the post year
$post_year = get_the_date('Y', $post_id);
// Assign the post to the term in the "post_date" taxonomy with the post year
$post_year_term_id = dp_loop_check_create_term( $post_year, $post_id);
if($post_year_term_id) {
// Get the post Month
$post_month = get_the_date('F', $post_id);
// Assign the post to the term in the "post_date" taxonomy with the post month
dp_loop_check_create_term( $post_month, $post_id, $post_year_term_id, $post_year);
}
}
}
// RUN FUNCTION AFTER THEME SETUP TO AVOID WP TAXONOMY DOES NOT EXIST ERROR
add_action( 'init', 'dp_set_publish_date_taxonomy_all_posts', 100);
function dp_loop_check_create_term($value, $post_id, $parent_term_id = null, $post_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.'-'.$post_year,
);
}
$new_term = wp_insert_term($value, 'post_date', $args);
if( $new_term && !is_wp_error($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