Having added a ‘word count’ admin column, I used this function from elsewhere on Stack to resave all posts and thus populate the word count (the wordcount function calculates on post-save).

With just a couple hundred posts/pages on a dedicated server with almost no public traffic, I thought I’d be alright to 'numberposts' => -1' and update all at once.

Seems not, as doing so sent the machine into a tizzy requiring a quick “what do I now?” call to support – who reported “there were many Apache child processes running, leading the server to an average load of 120%” and disabled wp-cron.php.

I’d already commented-out the function, so assume that once-started the processes continued in an Automattic-induced meltdown. (Perhaps not – I don’t pretend to understand this, and am happy to be educated.)

Three questions:

  1. I’m safe to re-enable wp-cron.php?
  2. Next time I’m tempted to use this, I shouldn’t use 'numberposts'
    => -1'
    . Perhaps stick to something like 'numberposts' => 10'?
  3. What upset the server – was it the word-count, or just re-saving
    two hundred posts?

The word count code from this question is below:

add_action('save_post', function($post_id, $post, $update) {
    $word_count = explode(" ", strip_shortcodes($post->post_content));
    update_post_meta($post_id, '_wordcount', count($word_count));
}, 10, 3);
add_filter('manage_posts_columns', function($columns){
    $columns['wordcount'] = 'Word count';
    return $columns;
});
add_action('manage_posts_custom_column', function($name) {
    global $post;

    if($wordcount === '')
         $wordcount="not counted";
    if($name === 'wordcount')
        echo $wordcount;
 });

Day-after update…

In response to requests I’m adding the ‘update all posts’ code to which I originally linked.

function example_hide(){
$my_posts = get_posts( array('post_type' => 'post', 'numberposts' => -1 ) );
foreach ( $my_posts as $my_post ):
wp_update_post( $my_post );
endforeach;
}
add_action('init','example_hide');

I first ran the update with ‘numberposts’ => 10′ and it completed in seconds – hence my decision to switch to -1.

1 Answer
1

rule of thumb, never do anything that results in DB write from the front end. Even better if you can create an admin page in which the operation is triggered (even if it just starts an AJAx based process).

Your problem here is with hooking on an inappropriate hook. You hooked on init which means that for each request the code to change all your posts is being run. Since this is a heavy operation it overloaded you DB and therefor your server. I am not sure why cron was singled out here.

As an additional note, your save handler is not great, you should make sure you are handling the post type you want and not revisions or auto saves.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *