WP Statistics is a popular and powerful WordPress plugin for tracking statistics on your WordPress website.
However if you have any plugins or anything that creates dynamic pages that don’t have a post id assigned to them then you will get lots of errors in your web server error logs like this:
WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 for query SELECT `page_id` FROM wp_statistics_pages WHERE `date` = '2020-11-13' AND `type` = '' AND `id` = made by require('wp-blog-header.php'), wp, WP->main, WP->parse_request, do_action_ref_array('parse_request'), WP_Hook->do_action, WP_Hook->apply_filters, rest_api_loaded, WP_REST_Server->serve_request, WP_REST_Server->dispatch, WP_Statistics_Rest->hit, WP_Statistics_Hits->Pages'
One method to get rid of the error is to disable the Track all pages setting in WP Statistics Settings. However by doing this it will no longer log these dynamically generated pages anymore and also doesn’t seem to log custom post types either, among various other things, so this option is unacceptable.
After trying out various things I settled on modifying the query by using the query filter like this:
/**
* Intercepts database queries.
*
* @param $query
*
* @return string
*/
function fix_wp_statistics_query( $query ) {
// intercept WP Statistics query to prevent error log spam on listings page because it has no post id
if ( strpos( $query, 'SELECT `page_id` FROM wp_statistics_pages WHERE `date`' ) !== false ) {
if ( substr( $query, - 2 ) == '= ' ) {
$query .= '0';
}
}
return $query;
}
add_filter( 'query', 'fix_wp_statistics_query' );
This will check every database query for the right query by comparing the start of the string before the date. If that matches it’ll check if the query ends with ‘= ‘ which is what happens when there is no post id and what causes the MySQL error. Then it will tack on a 0 to the end of the query so that it’s a valid MySQL query thereby stopping the error log spam. The page still works, things still work ok.
One thing I thought about doing is creating a dummy page for using it’s post id instead of 0 but then there may be more than a single page without a post id on the site so I figured it was kind of pointless. It seems to still work and I haven’t seen any other errors occurring from this change so far.
There are probably some other ways to go about it and maybe something better, ideally there would be a fix applied to the plugin itself but for now this is how I’ve done it. If you’ve found a better way please let me know.