SQL 更新到 WordPress 4.8.2 后出现语法错误

SQL Syntax Error after updating to WordPress 4.8.2

我一直在使用 Advanced Custom Fields 插件 (load_field) 中的挂钩,该挂钩将对象从我数据库中的 table 加载到 ACF select 字段。 table ('wp_new_royalsliders') 是由 RoyalSlider 图像滑块插件创建的,因此我使用挂钩使用滑块名称填充 select 字段。

此功能在很长一段时间内都运行良好,但最近停止运行 - 我认为在将核心更新到 4.8.2 之后:

    add_filter('acf/load_field/name=media_gallery_slider', 'my_acf_royalslider_choices');

    function my_acf_royalslider_choices($field){

      $field['choices'] = array();

      global $wpdb;

      $query = $wpdb->prepare('SELECT * FROM %1$s ORDER BY ID ASC', 'wp_new_royalsliders');
      $results = $wpdb->get_results($query);

      if(!empty($results)) :

      foreach($results as $result) :

          $value = $result->id;
          $label = $result->name;

          $field['choices'][ $value ] = $label;

      endforeach;
      endif;
      return $field;

    }

当我打开调试时出现错误:

WordPress 数据库错误:[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 '%1$s ORDER BY ID ASC' at line 1] SELECT * FROM %1$s ORDER BY ID ASC

当你传入一个硬编码的字符串值时,你不需要占位符,你可以只使用

$query = $wpdb->prepare('SELECT * FROM wp_new_royalsliders ORDER BY ID ASC');

如果你想要花哨和便携,你可以选择

$query = $wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'new_royalsliders ORDER BY ID ASC');

所以它也适用于其他前缀,但如果这是一个非常自定义的东西,不会进入任何其他站点,则可能没有必要。

似乎其他人也注意到了这种可能性的消除,请参阅 this request

更新:因为 $wpdb->prepare() 需要第二个参数(因为它的工作是转义变量输入以便在 SQL 中使用),它可能会抱怨。解决方案:去掉它,把你的 SQL 直接给 get_results:

$results = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'new_royalsliders ORDER BY ID ASC');