I have a WordPress-driven site on which I use wp-super-cache, and I am therefor forced to track views by ajax and not inline PHP. The following is the guts of my PHP file that gets called via ajax. The code isn’t really WordPress specific btw, but to explain it a little bit, it updates the wp_postmeta table just like update_post_meta() does. It uses mysqli, and makes 2 sql queries to
- Make sure the postid to update is valid.
- Increment the view-count.
My question is, is there some performance issues with this code, could it be better somehow?
Excerpt of code:
#...ajax stuff
$json_array = array();
$json_array["category_id"] = (int)$cat_id;
$json_array["post_id"] = (int)$post_id;
// get secure database credentials
require("/server/abspath/dbinfo.inc");
$db_details = new dbCreds;
$mysqli = new mysqli(
$db_details->get("dbhost"),
$db_details->get("dbuser"),
$db_details->get("dbpw"),
$db_details->get("db")
);
# test if valid post
# sql call no1
$valid_post_sql = "SELECT ABS(meta_value) FROM wp_postmeta "
. "WHERE (post_id = '" . $post_id . "' AND meta_key = 'views')";
$current_view_count = @$mysqli->query($valid_post_sql)->fetch_array();
$valid_post_sql_result = $current_view_count ? true : false;
if ( $valid_post_sql_result == false ) {
die("4");
}
# set new view-count
$views = isset($current_view_count[0]) && (int)$current_view_count[0] >= 0
? ((int)$current_view_count[0]+1) : 0;
# if not an admin or no views recorded yet
if ( !$is_admin || $views == 0 ) {
# sql call no2
$increment_imgviews_sql = "UPDATE wp_postmeta SET meta_value = "
. "meta_value + 1 WHERE (post_id = '" . $post_id
. "' AND meta_key = 'views')";
$mysqli->query($increment_imgviews_sql);
}
$json_array["views"] = $views;
return $json_array;
New code:
This is what i ended up using, replacing the 2 calls with just this single one:
UPDATE wp_postmeta SET meta_value = meta_value + 1 WHERE post_id = '" . $post_id . "' AND meta_key = 'views';
Note! This makes the return response obsolete, as I don’t get the current view-count returned. But on the other hand I save a query.
Looks perfectly fine to me. Only thing i would say is that if this is a background task, then getting the view count response is of no use in a production environment (unless something happens im no aware of).
So given that information, there’s no reason to validate the postid beforehand. You could drop the first sql statement along with the $views calculation, and just use the update statement (if its not a valid id, then it simply wont update anything). If you do not setup this “views” meta key when a post is created, then look at
INSERT... ON DUPLICATE KEYinstead of updatesIf you really want to keep your json response, then i can’t see any improvements that can really be made.