Skip to content

Instantly share code, notes, and snippets.

@nylen
Last active December 20, 2021 09:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nylen/abc5969a7bda5b3531edf84dfe9166ba to your computer and use it in GitHub Desktop.
Save nylen/abc5969a7bda5b3531edf84dfe9166ba to your computer and use it in GitHub Desktop.
Fix MySQL errors with WordPress + DigitalOcean managed MySQL

When running WordPress or ClassicPress using a DigitalOcean managed MySQL database you may experience errors like the following:

Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'dbname.wp_posts.post_date' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by for query SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/themename/404.php'), the_widget, WP_Widget_Archives->widget, wp_get_archives

Expression #1 of ORDER BY clause is not in SELECT list, references column 'dbname.wp_posts.post_date' which is not in SELECT list; this is incompatible with DISTINCT for query SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month FROM wp_posts WHERE post_type = 'attachment' ORDER BY post_date DESC made by wp_enqueue_media

More information including a suggested core patch is available at https://core.trac.wordpress.org/ticket/48377. In the meantime you can drop the mysql-no-ansi.php file into the wp-content/mu-plugins/ folder of your site to fix this issue, or add the code into your theme's functions.php file.

<?php
if ( ! defined( 'ABSPATH' ) ) {
return;
}
add_filter( 'incompatible_sql_modes', function( $incompatible_modes ) {
$incompatible_modes[] = 'ANSI';
return $incompatible_modes;
} );
$GLOBALS['wpdb']->set_sql_mode();
@nylen
Copy link
Author

nylen commented Feb 24, 2020

This change is slated to be included in WordPress 5.4 (https://core.trac.wordpress.org/ticket/48377) and ClassicPress 1.2.0 (ClassicPress/ClassicPress#558).

@devesh111
Copy link

I found this code with my modification to take care of this error if you run into it.
add_action( 'init', 'mysql_set_sql_mode_traditional', -1);
function mysql_set_sql_mode_traditional() {
global $wpdb;
$wpdb->query("SET SESSION sql_mode = 'TRADITIONAL'");
$wpdb->query("SET SESSION sql_mode = 'NO_ZERO_DATE'");
$wpdb->query("SET SESSION sql_mode = 'NO_ZERO_IN_DATE'");
}
Add it into your function.php theme file or a file in mu-plugin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment