I'm counting post views on a custom field inside wp_postmeta, the update happens each time a user interacts with the post. I was reading at this response Will a large postmeta table slow a site down? specifically:
"You should not write to the DB on front end requests" is the eleventh commandment. Your performance will deteriorate due to the writes locking down the table much more than the impact the size of the table will have.
You should probably write such data in files instead of DB, or at least use a different table.
So the idea is to accumulate these views on a new table and update the wp_postmeta with a WP-Cron function every hour or so. My question is: would this be bad for performance? Should I do it differently? or is it OK? I guess it will be about 500-1000 rows each run. Code:
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM total_views", OBJECT );
foreach($results as $key=>$value){
//for new posts without meta
$old_count = 0;
if ( metadata_exists( 'post', $value->post_id, 'post_views' ) ) {
$old_count = get_post_meta( $value->post_id, 'post_views', true );
}
new_count = $value->post_views;
$total_count = $old_count + $new_count;
update_post_meta( $value->post_id, 'post_views', $total_count );
}
//done. empty table
$wpdb->query('TRUNCATE TABLE total_views');
I should add I'm interested on keeping wp_postmeta updated because other site functionality depends on it. Else I would just stick to the new table.