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

如何通过MySQL中的Post ID获取并显示文章标题

解决方案

先修复原代码的SQL注入风险,同时实现将postid替换为对应文章标题的需求,修改后的代码如下:

<div>
    <?php
    global $wpdb;
    $current_user = wp_get_current_user();
    $user_id = $current_user->ID;
                                                                 
    // 用prepare防止SQL注入,同时关联wp_posts表直接获取标题(方案1:联表查询)
    $result = $wpdb->get_results( 
        $wpdb->prepare(
            "SELECT wt.*, p.post_title FROM wp_test wt LEFT JOIN wp_posts p ON wt.postid = p.ID WHERE wt.userid = %d ORDER BY wt.arrival ASC",
            $user_id
        )
    );
    
    foreach ( $result as $print ) : ?>
    <div style="margin-bottom:20px;">
        <h3 style="font-size:1.5rem;">
            <?php 
            // 方案1:输出联表查询到的标题,无对应文章则显示原postid
            echo !empty($print->post_title) ? $print->post_title : $print->postid;
            
            // 方案2:用WordPress内置函数get_the_title,自动处理文章不存在的情况
            // echo get_the_title($print->postid) ?: $print->postid;
            ?>
        </h3>
    </div>
    <?php endforeach; ?>
</div>

关键修改说明

  • SQL注入防护:替换直接拼接$user_id的写法,用$wpdb->prepare()绑定参数,这是WordPress开发的安全标准操作。
  • 两种标题获取方式:
    • 联表查询:一次数据库请求同时获取wp_test和wp_posts的数据,减少查询次数,适合数据量较大的场景。
    • 内置函数get_the_title():WordPress原生函数,自动处理文章不存在的情况(返回空字符串),同时支持标题过滤钩子,更贴合WP生态规范。
  • 容错处理:当postid对应文章不存在时,默认显示原postid,避免页面出现空白内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:22:51