0

I have a Custom Post Type which fetches some data every day for each post and I need to store new values while keeping the old ones. If I use this, it will overwrite previous data:

update_post_meta(get_the_ID(), 'temperature', 25);
update_post_meta(get_the_ID(), 'humidity', 70);
update_post_meta(get_the_ID(), 'ph', 7);

So I was thinking about using something like this to append time to name:

    update_post_meta(get_the_ID(), 'temperature-' . time(), 'some_value');
    update_post_meta(get_the_ID(), 'humidity-' . time(), 'some_value');

I got all this working, and now I got to the point where I want to retrieve the latest two data for each post - values for yesterday and today. This is where I got stuck.

Is there an easier/Wordpress way for saving the different data every day for every variable inside every CTP post?

When retrieving these variables I was hoping to do it something like this, but maybe I have complicated more than I should have?

  $args = array(
        'post_type' => 'myctp',
        'posts_per_page' => -1 // Retrieve all CTP posts
        );
  $query = new WP_Query($args);

    if($query->have_posts())   :
         while($query->have_posts())  {

             $query->the_post();
             $post_meta = get_post_meta(get_the_ID());

             // here get only 2 latest values for temperature, humidity, ph...

         }
    endif;
2
  • 1
    How many mycpt do you have? Have you considered a custom table instead of storing all the data points as post meta?
    – birgire
    Commented Dec 5, 2016 at 14:27
  • Yeah, I tried it later with a custom table but in the end I decided to go with Laravel Commented Dec 5, 2016 at 22:50

1 Answer 1

1

I'm agree with the comment of @birgire, but if you really want to do it with custom fields, I think it's better to group all datas for a post in one custom field in an array.

After, you only need to use get_post_meta to get older values and add the new one in the array. Eventually, you could apply a php function to the array limite to 5 days. update_post_meta will save it as an array, to get it in your template, just create a display function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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