fix: sql_query auto-translates wp_ prefix to actual WP table prefix

This commit is contained in:
2026-06-02 11:43:17 +00:00
parent 86e5362d85
commit d6c2b86863
+7 -6
View File
@@ -34,11 +34,17 @@ class RawSqlTools {
}
}
// Auto-translate wp_ table references to the actual WP prefix
// e.g. on a site with prefix "mwp_", "wp_posts" becomes "mwp_posts"
global $wpdb;
if ($wpdb->prefix !== 'wp_') {
$sql = preg_replace('/\bwp_([a-zA-Z0-9_]+)\b/', $wpdb->prefix . '$1', $sql);
}
if (!preg_match('/\bLIMIT\b/i', $sql)) {
$sql .= " LIMIT $limit";
}
global $wpdb;
$results = $wpdb->get_results($sql, ARRAY_A);
if ($wpdb->last_error) {
@@ -69,18 +75,13 @@ class RawSqlTools {
$table = sanitize_text_field($args['table'] ?? '');
if (empty($table)) throw new \RuntimeException("table is required.");
// Accept the table name with or without the WP prefix.
// If the caller passes "wp_posts" and the actual prefix is "mwp_", try both.
if (strpos($table, $wpdb->prefix) !== 0) {
// Maybe they passed "wp_posts" on a site with a different prefix — strip any leading wp_ and re-add correct prefix
$stripped = preg_replace('/^wp_/', '', $table);
$candidate = $wpdb->prefix . $stripped;
// Verify the candidate exists
$exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $candidate));
if ($exists) {
$table = $candidate;
} else {
// Last attempt: use exactly as given
$exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table));
if (!$exists) {
throw new \RuntimeException("Table not found: {$args['table']}. WP prefix is: {$wpdb->prefix}");