How can I Update Post Meta of all my published posts in WordPress to show current date and time each time any visitor click the post? Like a custom code in theme function to modify the the single post page to show current date and time for the visitors on each visit
I tried using this code below but didn’t work..
$time = current_time('mysql');
$post_type = 'post'; // post, page, product or some other custom post type
// Get all the posts
$posts = get_posts( array(
'post_status' => 'published',
'post_type' => $post_type
));
foreach( $posts as $post ) {
// We only want to update the post date
$update = array(
'ID' => $post->ID,
'post_date' => $time,
'post_date_gmt' => get_gmt_from_date( $time ),
);
//* Update the post
wp_update_post( $update );
2
Answers
The code you’ve provided is not updating the post meta instead, it’s attempting to update the post date. Also, there are some small issues in your code snippet. Here’s how you could achieve what you’re looking for:
I found a couple of issues in your code:
You need to replace:
'post_status' => 'published'
to'post_status' => 'publish'
Also, if you want to get all posts, you need to add
'posts_per_page' => -1
So, the code will be like this:
If you want to use custom post fields to save the date, you can try this example:
But if your site has many posts, these examples are not suitable because they result in multiple database requests.
I recommend using alternative methods. Here’s an example for updating post data:
And here’s an example for updating the custom post meta: