如何通过query()获取WordPress文章并输出为JSON格式?
代码问题分析
现有代码有两个核心问题导致无法输出符合要求的JSON数组:
- WordPress内置函数
the_permalink()、the_title()默认是直接打印输出内容,不会将值返回给赋值的变量,需要用带返回值的get_permalink()、get_the_title()替代 - 循环内直接输出单条文章的JSON结构,最终会输出多个拼接的独立JSON对象,不是完整的数组结构,需要先把所有文章数据存入全局数组,循环结束后统一转JSON输出
修正后可用代码
<?php require('/home/dealicopter/public_html/wp-load.php'); // 声明返回内容为JSON格式 header('Content-Type: application/json; charset=utf-8'); function wpdocs_custom_excerpt_length( $length ) { return 20; } add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 ); $args = array( 'posts_per_page' => 10, 'cat' => 7, ); // 初始化存储所有文章的数组 $post_list = []; query_posts($args); if (have_posts()) : while (have_posts()) : the_post(); $permalink = get_permalink(); $title = get_the_title(); // 单条文章数据推入全局数组 $post_list[] = [ 'id' => $permalink, 'title' => $title // 如需更多字段可在此追加,例如 'excerpt' => get_the_excerpt(), 'post_time' => get_the_date('Y-m-d H:i:s') ]; endwhile; else: $post_list = []; endif; wp_reset_query(); // 统一输出JSON数组,JSON_UNESCAPED_UNICODE避免中文被转义 echo json_encode($post_list, JSON_UNESCAPED_UNICODE); ?>
内容的提问来源于stack exchange,提问作者Aayush Gupta
相关产品推荐
相关产品推荐

