2

I have managed to update post meta using update_post_meta(). However, the more posts I have, the more time it takes. I would like to minimize the time it takes to process say about 400 posts (although I am not too sure how long this will take). Currently my code looks like this:

    $numbers = range(1,100000);
    shuffle($numbers); //Randomizing the index (no duplication at all)

    $count = 0; //Begin with an index of 0

    $args = array(
        'post_type' => 'xn_group',
        'post_status' => 'publish'
    );


    //This should get all the posts of xn_group, all of these posts will get the value of its meta_key 'xn_group_order' shuffled (randomized daily).
    $the_query = new WP_Query($args);

    //DIRECT QUERYING...(to reduce time complexity)

    while($the_query->have_posts()) : $the_query->the_post();

        update_post_meta(get_the_ID(), "xn_group_order", $numbers[$count]);
        //$count += mt_rand(1,10); //Another technique to ensure fair randomization (not necessary).
        $count += 1;

    endwhile;

    wp_reset_query();

However, I worry that as posts get bigger, the changes made will cost a lot. So I would like to ask the better way to achieve this. Perhaps using SQL statement? Any ideas?

  • In case of 400 or more posts it is possible that you will run out of memory just by the query. – Mark Kaplun Oct 15 '14 at 8:33
  • then do you have any creative idea so as to minimise the memory usage? – wordwannabe Oct 15 '14 at 9:35
  • @courtny's answer will naturally force that, otherwise make smaller queries like only 100 at a time and reuse the variable to free previous memory – Mark Kaplun Oct 15 '14 at 13:36
1

Perhaps using SQL statement?

Direct SQL queries are very dangerous, especially when updating the DB. At the very least you will get any object cache out of sync and you might miss execution of import action and filters.

If this update is something that is rarely done it is better that it will take one more minute then to risk the integrity of your system.

  • okay thank you. I will refrain from using direct SQL queries when updating the DB. – wordwannabe Oct 15 '14 at 9:36
1

For intensive processes like this, it might be best to schedule a WP cron event to handle the process on a daily or twice daily schedule.

Checkout this WP Codex page for the wp_schedule_event() function

  • that is exactly what I have done so it should execute once a day but this is pretty difficult to check whether the code gets executed or not and I heard that there can possibly be a lag here :( – wordwannabe Oct 15 '14 at 9:34

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.