如何获取WordPress内容并转为JSON?PHP连接MySQL遇问题
问题分析与解决方案
你的核心错误是混淆了WordPress模板函数与MySQL数据库字段:the_title()和the_content()是WordPress的PHP输出函数,并非othpk_posts表中的字段名,数据库中对应的实际字段是post_title(标题)和post_content(原始内容)。
以下是两种修正方案:
方案一:原生MySQL直接获取(无WordPress环境依赖)
直接使用数据库真实字段名获取数据,适合独立脚本场景:
<?php // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 仅查询需要的字段,提升性能 $sql = "SELECT ID, post_title, post_content FROM othpk_posts WHERE post_type='product' AND post_status='publish'"; $result = $conn->query($sql); if ($result->num_rows > 0) { $data = array(); while($row = mysqli_fetch_array($result)) { array_push($data, array( 'id' => $row['ID'], 'productName' => $row['post_title'], 'productContent' => $row['post_content'] )); } $json = json_encode($data); echo $json; } else { echo "0 条结果"; } $conn->close(); ?>
方案二:使用WordPress内置函数(推荐)
如果脚本在WordPress环境中运行(如主题/插件文件),建议用WP原生方法,自动处理内容过滤、短代码解析等:
<?php // 若脚本不在WP目录下,需引入WP核心文件 // require_once('/你的WordPress路径/wp-load.php'); $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1 // 获取所有已发布产品 ); $products = get_posts($args); $data = array(); foreach ($products as $product) { $data[] = array( 'id' => $product->ID, 'productName' => get_the_title($product->ID), 'productContent' => apply_filters('the_content', $product->post_content) ); } echo json_encode($data); ?>
说明:
get_the_title()返回处理后的标题(区别于直接输出的the_title())apply_filters('the_content', ...)等价于the_content()的返回版本,会自动解析短代码、格式化段落等
内容的提问来源于stack exchange,提问作者Khurram80
相关产品推荐
相关产品推荐

