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

WordPress自定义函数调用get_results遇unexpected T_STRING错误求助

解决get_top_terms函数的unexpected T_STRING错误

你的代码出现语法错误的核心原因是SQL字符串的双引号嵌套冲突,同时SQL语句本身也存在统计字段不明确的问题,修复方案如下:

错误分析

  1. 你用双引号包裹整个SQL字符串,但内部的"post_tag"同样使用双引号且未转义,PHP解析时会将其识别为字符串结束标记,触发unexpected T_STRING错误。
  2. SQL中的count DESC未指定统计对象,数据库无法识别要统计的内容,会导致查询失效。

修复后的代码

function get_top_terms(){
    global $wpdb;
    $termsSQL = 'SELECT DISTINCT AN_terms.name, count(*) as term_count 
                 FROM AN_posts 
                 INNER JOIN AN_term_relationships ON AN_term_relationships.object_id = AN_posts.ID 
                 INNER JOIN AN_term_taxonomy ON AN_term_taxonomy.term_taxonomy_id=AN_term_relationships.term_taxonomy_id 
                 INNER JOIN AN_terms ON AN_term_taxonomy.term_id=AN_terms.term_id 
                 WHERE AN_posts.post_date_gmt >= NOW() - INTERVAL 1 DAY 
                   AND AN_term_taxonomy.taxonomy = "post_tag" 
                 GROUP BY AN_terms.name 
                 ORDER BY term_count DESC 
                 LIMIT 5';
    $tResults = $wpdb->get_results($termsSQL);
    print_r($tResults);
}
add_shortcode( 'topTerms', 'get_top_terms');

关键修改点

  • 字符串嵌套处理:将SQL字符串的外层改为单引号,内部的"post_tag"可保留双引号(或换成单引号),避免PHP解析冲突。
  • 统计字段明确:将count DESC改为count(*) as term_count,通过别名term_count排序,确保数据库能正确统计每个标签的出现次数。
  • 代码可读性优化:对SQL语句进行换行排版,结构更清晰,便于后续维护。

更安全的版本(推荐)

使用WordPress内置的$wpdb->prepare方法,避免SQL注入风险:

function get_top_terms(){
    global $wpdb;
    $taxonomy = 'post_tag';
    $termsSQL = $wpdb->prepare(
        'SELECT DISTINCT AN_terms.name, count(*) as term_count 
         FROM AN_posts 
         INNER JOIN AN_term_relationships ON AN_term_relationships.object_id = AN_posts.ID 
         INNER JOIN AN_term_taxonomy ON AN_term_taxonomy.term_taxonomy_id=AN_term_relationships.term_taxonomy_id 
         INNER JOIN AN_terms ON AN_term_taxonomy.term_id=AN_terms.term_id 
         WHERE AN_posts.post_date_gmt >= NOW() - INTERVAL 1 DAY 
           AND AN_term_taxonomy.taxonomy = %s 
         GROUP BY AN_terms.name 
         ORDER BY term_count DESC 
         LIMIT 5',
        $taxonomy
    );
    $tResults = $wpdb->get_results($termsSQL);
    print_r($tResults);
}
add_shortcode( 'topTerms', 'get_top_terms');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:41:02