0

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' );
  • There are a few approaches to this, but firstly, you will need to fix your code with: update_post_meta( get_the_ID(), 'year_date', $year_published ); – Christine Cooper Dec 3 '18 at 12:54
  • Thanks Christine. could you suggest one short approach? I would like to update all existing and future posts. Preferably without using a plugin? – Qjoey Dec 3 '18 at 12:58
  • 1
    I suggest hooking into save post and storing the custom meta data. And also looping through all existing posts and updating the value... – Christine Cooper Dec 3 '18 at 14:12
  • So I managed to loop through and update the values... However, when I inspect post meta fields, both the month and year are only storing empty strings ' ' instead of the actual value. Please see my answer below and help point out any edits to fix this. – Qjoey Dec 3 '18 at 21:38
0

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?

  • Yes, you need to add the $post_id, like this: $month=get_the_date('M', $post->ID);... Do the same with the $year one. =) – Christine Cooper Dec 4 '18 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.