fix: sql_query auto-translates wp_ prefix to actual WP table prefix
This commit is contained in:
@@ -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)) {
|
if (!preg_match('/\bLIMIT\b/i', $sql)) {
|
||||||
$sql .= " LIMIT $limit";
|
$sql .= " LIMIT $limit";
|
||||||
}
|
}
|
||||||
|
|
||||||
global $wpdb;
|
|
||||||
$results = $wpdb->get_results($sql, ARRAY_A);
|
$results = $wpdb->get_results($sql, ARRAY_A);
|
||||||
|
|
||||||
if ($wpdb->last_error) {
|
if ($wpdb->last_error) {
|
||||||
@@ -69,18 +75,13 @@ class RawSqlTools {
|
|||||||
$table = sanitize_text_field($args['table'] ?? '');
|
$table = sanitize_text_field($args['table'] ?? '');
|
||||||
if (empty($table)) throw new \RuntimeException("table is required.");
|
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) {
|
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);
|
$stripped = preg_replace('/^wp_/', '', $table);
|
||||||
$candidate = $wpdb->prefix . $stripped;
|
$candidate = $wpdb->prefix . $stripped;
|
||||||
// Verify the candidate exists
|
|
||||||
$exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $candidate));
|
$exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $candidate));
|
||||||
if ($exists) {
|
if ($exists) {
|
||||||
$table = $candidate;
|
$table = $candidate;
|
||||||
} else {
|
} else {
|
||||||
// Last attempt: use exactly as given
|
|
||||||
$exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table));
|
$exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table));
|
||||||
if (!$exists) {
|
if (!$exists) {
|
||||||
throw new \RuntimeException("Table not found: {$args['table']}. WP prefix is: {$wpdb->prefix}");
|
throw new \RuntimeException("Table not found: {$args['table']}. WP prefix is: {$wpdb->prefix}");
|
||||||
|
|||||||
Reference in New Issue
Block a user