自定义WordPress PHP API扩展:获取更多文章字段及分类信息
WordPress自定义API扩展文章字段解决方案
问题背景
开发适配WordPress的应用时,通过自定义PHP API获取文章列表,现有代码可返回ID、标题等10项信息,但需要扩展更多字段(如文章分类),同时不清楚post_title这类字段的获取逻辑及更多字段来源。
核心知识点说明
1. 基础字段的来源与获取
get_posts()返回的每个$post对象是WP_Post类的实例,其属性直接对应WordPress数据库wp_posts表的字段。比如:
$post->post_title对应表中文章标题字段$post->post_content对应文章内容字段$post->post_modified对应文章最后修改时间$post->post_status对应文章状态(publish/draft等)
这些字段可以直接通过$post->字段名的方式读取,无需额外函数调用。
2. 扩展字段的获取方法
对于分类、标签、自定义字段这类不在wp_posts表中的数据,需要用WordPress内置函数获取:
- 文章分类:使用
get_the_category($post->ID),返回分类对象数组,可提取名称、ID、slug等信息 - 文章标签:使用
get_the_tags($post->ID),用法与分类类似 - 自定义字段:使用
get_post_meta($post->ID, '自定义字段键名', true)获取单个字段值
修改后的完整代码
function api_posts() { $args = [ 'numberposts' => 99999, 'post_type' => 'post', ]; $posts = get_posts($args); $data = []; foreach ($posts as $index => $post) { // 基础字段 $data[$index]['id'] = $post->ID; $data[$index]['title'] = $post->post_title; $data[$index]['excerpt'] = $post->post_excerpt; $data[$index]['content'] = $post->post_content; $data[$index]['slug'] = $post->post_name; $data[$index]['date'] = $post->post_date; $data[$index]['modified_date'] = $post->post_modified; // 新增修改时间 $data[$index]['post_url'] = get_permalink($post->ID); // 缩略图字段 $data[$index]['thumbnailImage'] = get_the_post_thumbnail_url($post->ID, 'thumbnail'); $data[$index]['mediumImage'] = get_the_post_thumbnail_url($post->ID, 'medium'); $data[$index]['largeImage'] = get_the_post_thumbnail_url($post->ID, 'large'); // 文章分类 $categories = get_the_category($post->ID); $data[$index]['categories'] = []; if (!empty($categories)) { foreach ($categories as $cat) { $data[$index]['categories'][] = [ 'id' => $cat->term_id, 'name' => $cat->name, 'slug' => $cat->slug ]; } } // 文章标签(可选) $tags = get_the_tags($post->ID); $data[$index]['tags'] = []; if (!empty($tags)) { foreach ($tags as $tag) { $data[$index]['tags'][] = [ 'id' => $tag->term_id, 'name' => $tag->name, 'slug' => $tag->slug ]; } } // 自定义字段示例(替换为你的实际字段键名) $data[$index]['custom_field'] = get_post_meta($post->ID, 'your_custom_key', true); } return $data; }
额外提示
- 如果需要更多WP_Post属性,可以直接打印
$post对象查看所有可用字段:var_dump($post) - 对于自定义分类法,使用
get_the_terms($post->ID, '自定义分类法slug')获取
内容的提问来源于stack exchange,提问作者mesh
相关产品推荐
相关产品推荐

