Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

How to add a new meta key and assign timestamp to posts

A very simplistic method of achieving this would be as follows;

add_action('template_redirect', 'recently_read');
function recently_read(){

    global $post;

    //only run this function for the posts post_type
    if ( !is_single() ) 
        return;

    //get the current time in the format of: 2013-02-22 11:55:51 
    $timestamp = current_time('mysql'); 

    //add the $timestamp variable to the meta_key for this post
    update_post_meta($post->ID, 'reading_this', $timestamp);


}

Note: The above function goes into your theme functions.php file and is hooked onto the template_redirect action which is fired just before displaying the page to the user. At this point, behind the scenes, our recently_read function will fire and add a time stamp under the key reading_this (name it to your liking). This will occur each time this or any post is viewed. If a time stamp already exists for a given post, it will then update the time stamp accordingly.

Then to retrieve a list of posts with this key you would do the following in your theme files where you want those posts to display;

$recently_read = get_posts( 
    array(
        'posts_per_page'  => 5,       //how many posts we want to show at most
        'meta_key' => 'reading_this', //get posts by our meta key
        'orderby' => 'meta_value',    //order posts by the value stored in the key
        'order' => 'DESC'             //order posts in descending order (newest to oldest)
   )
); 

foreach ($recently_read as $read) {
    echo '<a href="'. get_permalink($read->ID) . '">'. $read->post_title .'</a>';
}

The above could be improved a number of ways but this will definitely get you started.

Note: This is void of any logic that determines if the post was viewed in the last X minutes. For that you can apply your own logic to the meta_key named reading_this and manipulate the data to your liking.

Related Posts:

  1. Ordering posts by anniversary using only day and month
  2. Displaying posts with only upcoming dates according their custom field date value
  3. Which is best in the following scenario : post_meta vs custom table vs parent/child posts
  4. How do I have WP_Query match posts based on search parameter OR meta fields? (rather than search parameters AND meta fields)?
  5. Ordering posts by custom field named “date” in backend
  6. Unique meta_key with array value vs repeated meta_key with single values
  7. Avoiding ACF get_field and returning to core WordPress function
  8. change order of images attached to post
  9. How to improve my non-unique metadata MySQL entries?
  10. WP Query Args – search by meta_key or title
  11. SQL query based on two different custom field values
  12. Using meta query (‘meta_query’) with a search query (‘s’)
  13. Can I exclude a post by meta key using pre_get_posts function?
  14. Custom post meta field effect on the performance on the post
  15. How to get custom post meta using REST API
  16. Difference between meta keys with _ and without _ [duplicate]
  17. Orderby meta_value only returns posts that have existing meta_key
  18. What is the index [0] for on post meta fields?
  19. What is “meta_input” parameter in wp_insert_post() used for?
  20. How to enable revisions for post meta data?
  21. The “_encloseme” Meta-Key Conundrum
  22. ORDER BY custom field value
  23. Best way to programmatically remove a category/term from a post
  24. Using get_post_meta with new_to_publish
  25. Can I query custom meta data through WP_Query
  26. Add custom fields to search
  27. SELECT max(meta_value) FROM wp_postmeta WHERE meta_key=’price’… stops working when value is over 999
  28. Matching Serialized Arrays with meta_query
  29. Custom field metabox not showing in back-end
  30. Meta Query with AND & OR?
  31. So much data in postmeta
  32. Can I count the number of users matching a value in a multiple value key?
  33. Getting attachments by meta value
  34. When using add_post_meta and update_post_meta, is there any way to give the individual arrays keys?
  35. How to hide meta box values from custom fields list?
  36. Auto sort the wp-admin post list by a meta key
  37. get_post_meta() unserialize issue – returns boolean(false)
  38. What is the advantage of the wp_options design pattern?
  39. Storing meta fields multiple times OR once with multi dimensional array?
  40. Allow user to create instances of custom field
  41. display specific custom fields
  42. How Can I save multiple records in same meta key?
  43. Is there a hook / action that is triggered when adding or removing a post thumbnail?
  44. Date, Time, and Timezones
  45. Meta keywords and descriptions plugin for manually editing meta for each page/post
  46. passing argument to get_template_part() or a better way to code
  47. Is it possible to store arrays in a custom field?
  48. Get updated meta data after save_post hook
  49. Multiple meta values for same meta_key adding on “Preview Changes” hit but not on saving or updating post
  50. Save HTML formatted data to post meta using add_post_meta()
  51. Trying to perform complex custom field query with order by set to field value
  52. importing data from non-wordpress mysql db
  53. Is there a way to do multiple ordering on a multiple meta_query?
  54. Create meta boxes that don’t show in custom fields
  55. Transients vs CRON +Custom Fields: Caching Data Per Post
  56. Unable to save datetime custom meta field using update_post_meta() function
  57. Up/Down voting system for WordPress
  58. post meta data clearing on autosave
  59. WordPress Search Custom Meta Field Only
  60. Create custom field on post draft or publish?
  61. Display info from custom fields in all images’ HTML
  62. Compare meta_query decimals not working right
  63. WordPress altering my custom query, How to fix it?
  64. Calling Specific Pages with wp query Part II
  65. Loop through two different sets of custom fields
  66. get_post_meta fields don’t show up on posts page
  67. Update meta values with AJAX
  68. How to break meta values into different items and avoid duplicates?
  69. copy attachments to another post type and change attachment url
  70. Cannot edit post meta fields with rest API
  71. ajax delete value from custom field array
  72. Save attachment custom fields on front end
  73. Slow meta query with multi meta keys
  74. How to use pagination with get_post_meta
  75. Copying Custom Meta Values from existing post to a duplicate post
  76. Using OR in WP_Query negates the “NOT EXISTS” compare
  77. Add a post meta key and value only if it does not exist on the post
  78. How can I query on the year part of a complete date in a custom field?
  79. Move value of one custom field to another
  80. Order posts according to user defined order for meta values?
  81. How can I combine meta_query queries?
  82. custom field value date convert to unix timestamp problems
  83. Custom fields to save multiple values
  84. Custom fields: In what order are they saved into the DB?
  85. Function to change meta value in database for each post
  86. Get a post_id where meta_value equals something in a serialized meta_value field
  87. Get aggregate list of all custom fields for entire blog
  88. Difference between ‘LIKE’ and ‘IN’ in meta queries
  89. Transition from (classical) serialized custom meta field to (gutenberg) rest enabled meta
  90. Unable to show ACF’s Image Custom Field properly in Genesis Framework [closed]
  91. Sorting posts by multiple values, combined
  92. Custom field value based on other custom field values
  93. meta_value_num sort glitch
  94. WP_Query display next custom post from today’s date
  95. wp_handle_upload error “Specified file failed upload test” but still creates attachment?
  96. How to save a ToggleControl value in a meta field?
  97. WP_Meta_Query causing long-running MySQL queries
  98. Saving custom image meta fields
  99. Author Page Custom Query WHERE author OR [post meta value] OR [post meta value]
  100. What Is meta_id In wp_postmeta?
Categories custom-field Tags custom-field, meta-query, post-meta, timestamp
Using wp_list_categories like the the_category (showing just current categories of a post)
How can I automatically insert the page content as the title?

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Post Navigation Elementor
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • WPFacet multiple loop displaying duplicate content
  • Get the name of the template/*html file used
  • Fix: WordPress.DB.PreparedSQL.NotPrepared Plugin Check (PCP)
  • Removing unnecessary CSS and JS code from wp_head()
  • hexagonal image gallery. Am I on the right track? [closed]
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress