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

如何在WordPress导出JSON时提取分类名与链接并按分类拆分JSON

代码修复说明

  • 原代码问题1:get_the_category()参数错误,且直接返回全量分类对象导致冗余字段,调整为先获取分类对象后仅提取所需的分类名称、分类链接字段
  • 原代码问题2:未定义$category_id变量,导致分类链接获取失败
  • 新增按分类拆分导出逻辑:以分类别名为文件名标识,每个分类对应单独的JSON文件,仅存储归属该分类的文章数据,额外增加JSON_UNESCAPED_UNICODE参数避免中文乱码

完整修正代码

function export_posts_in_json() {
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 10, // 如需导出全量文章可改为 -1
    );

    $query = new WP_Query( $args );
    $posts_by_cat = array(); // 按分类分组存储文章

    while( $query->have_posts() ) : $query->the_post();
        // 获取文章所属分类
        $categories = get_the_category( get_the_ID() );
        if ( !empty( $categories ) ) {
            $current_cat = $categories[0];
            $cat_name = $current_cat->name;
            $cat_link = get_category_link( $current_cat->term_id );
            $cat_slug = $current_cat->slug;
        } else {
            // 未分类兜底逻辑
            $cat_name = '未分类';
            $cat_link = '';
            $cat_slug = 'uncategorized';
        }

        // 组装文章数据,仅保留所需字段
        $post_data = array(
            'id' => get_the_ID(),
            'date' => get_the_date(),
            'title' => get_the_title(),
            'link' => get_the_permalink(),
            'image' => get_the_post_thumbnail_url(),
            'category' => $cat_name,
            'categoryLink' => $cat_link
        );

        // 按分类别名分组
        $posts_by_cat[$cat_slug]['cat_info'] = array(
            'cat_name' => $cat_name,
            'cat_link' => $cat_link
        );
        $posts_by_cat[$cat_slug]['posts'][] = $post_data;

    endwhile;

    wp_reset_query();
    $upload_dir = wp_get_upload_dir();

    // 遍历分组,按分类导出单独JSON文件
    foreach ($posts_by_cat as $cat_slug => $cat_data) {
        $file_name = date('Y-m-d') . '-' . $cat_slug . '.json';
        $save_path = $upload_dir['basedir'] . '/' . $file_name;
        $data = json_encode($cat_data, JSON_UNESCAPED_UNICODE);

        $f = fopen( $save_path , "w" ); 
        fwrite($f , $data);
        fclose($f);
    }
}

add_action( 'save_post', 'export_posts_in_json' );

如果需要支持单篇文章归属多个分类、并把文章同步写入所有关联分类的JSON文件,只需把单次取第一个分类的逻辑改为遍历$categories数组逐个写入分组即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 00:30:00