You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress环境下MariaDB SQL语法错误问题求助

Fixing MariaDB SQL Syntax Error in Your WordPress Query

Got it, let's break down the issue with your database query and get it working again.

First, the immediate syntax error comes from a small but critical mistake in your WHERE clause. You wrote:

$wpdb->posts.post_status = IN ('publish', 'future')

Combining the equality operator (=) with the IN operator is invalid SQL. The IN operator already checks if a value matches any item in the provided list, so the = is completely redundant here—and it's what's triggering that syntax error.

Fixed Query (Plus a Security Upgrade)

I've corrected that issue and also added a critical security improvement (using $wpdb->prepare() to avoid SQL injection risks, which you should always do when inserting variables into queries):

// Check if there are posts before our $date
$postA = $wpdb->get_row(
    $wpdb->prepare(
        "SELECT ID, post_date 
         FROM {$wpdb->prefix}posts 
         LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) 
         LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) 
         WHERE $wpdb->posts.post_status IN ('publish', 'future') 
           AND $wpdb->posts.post_type = 'post' 
           AND $wpdb->term_taxonomy.taxonomy = 'category' 
           AND $wpdb->term_taxonomy.term_id = 18 
           AND $wpdb->posts.post_date < %s 
         ORDER BY post_date DESC 
         LIMIT 1",
        $date
    )
);

Key Changes Made:

  • Removed the extra = before IN for the post_status check to resolve the syntax error.
  • Replaced the direct '{$date}' insertion with %s in the query string, paired with $wpdb->prepare() to safely pass the $date variable. This prevents SQL injection attacks, which is a must for WordPress database interactions.
  • Fixed a minor typo in the comment ("is posts" → "are posts") for clarity.

Quick Additional Checks:

If you still run into issues after applying this fix, verify two more things:

  • Ensure $date is formatted correctly for MariaDB (valid formats include YYYY-MM-DD or YYYY-MM-DD HH:MM:SS).
  • Confirm that term ID 18 actually exists in your wp_term_taxonomy table and is associated with the category taxonomy.

内容的提问来源于stack exchange,提问作者user6677795

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:02:12