I would like to update all my posts with a custom field that stores the year the post was published.
The "year" value will obviously be retrieved from the post's date meta data.
I will then use the value stored to query posts with a certain plugin.
So far, I have this, but not sure where this code should go and if it needs modification!
$year_published = get_the_date( 'Y' );
update_post_meta(get_the_ID(), 'year_date', '$year_published' );
I would like to update all my posts with a custom field that stores the year the post was published.
The "year" value will obviously be retrieved from the post's date meta data.
I will then use the value stored to query posts with a certain plugin.
So far, I have this, but not sure where this code should go and if it needs modification!
$year_published = get_the_date( 'Y' );
update_post_meta(get_the_ID(), 'year_date', '$year_published' );
So I was first looking for a way to loop through the existing posts, as suggested in Christine's comment. Based on this answer, I created a basic plugin that runs the loop upon activation.
// Run the loop when the plugin is activated
register_activation_hook(__FILE__, 'update_my_metadata');
function update_my_metadata(){
$args = array(
'post_type' => 'post', // Only get the posts
'post_status' => 'publish', // Only the posts that are published
'posts_per_page' => -1 // Get every post
);
$posts = get_posts($args);
foreach ( $posts as $post ) {
// Run a loop and update every meta data
$month=get_the_date('M');
$year=get_the_date('Y');
update_post_meta($post->ID, 'month-field', $month); echo $month;
update_post_meta($post->ID, 'year-field', $year); echo $year;
}
}
However, when I inspect post meta fields, both the month and year are only storing empty strings '' instead of the actual date value.
Any suggestions?
update_post_meta( get_the_ID(), 'year_date', $year_published );
– Christine Cooper ♦ Commented Dec 3, 2018 at 12:54