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

WordPress通过AJAX导入CSV时标题与内容正常,Post Meta(文章自定义字段)无法导入的技术求助

问题分析与解决方案

你代码里的核心问题是错误地使用了帖子参数数组去调用update_post_meta——wp_insert_post()函数返回的是创建成功的帖子ID,但你把$cpt_id定义成了帖子的参数数组,导致update_post_meta接收的不是合法的帖子ID,自然无法写入自定义字段。

修正后的代码

if(isset($_FILES['file'])){
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );
    
    $attachment_id = media_handle_upload( 'file', 0 );
    if ( is_wp_error( $attachment_id ) ) {
        wp_send_json(array(
            'message' => __( 'Failed to upload file: ' . $attachment_id->get_error_message(), 'gd-povestea-mea' )
        ));
        wp_die();
    }
    
    $attachment_url = wp_get_attachment_url( $attachment_id );
    $fp = fopen($attachment_url, 'r');
    if ( !$fp ) {
        wp_send_json(array(
            'message' => __( 'Failed to open CSV file', 'gd-povestea-mea' )
        ));
        wp_die();
    }
    
    $csvReader = new yidas\csv\Reader($fp, [ 'encoding' => 'UTF-8' ]);
    $firstRow = $csvReader->readRow();
    $remainingRows = $csvReader->readRows();
    
    foreach ($remainingRows as $key => $remainingRow){
        $post_args = array(
            'post_title'   => sanitize_text_field($remainingRow[0]),
            'post_content' => sanitize_text_field($remainingRow[0]), // 这里注意:标题和内容用了同一列?如果是笔误记得修正
            'post_type'    => 'quotations',
            'post_status'  => 'publish'
        );
        
        // 保存帖子并获取返回的ID
        $post_id = wp_insert_post( $post_args );
        
        // 检查帖子是否创建成功
        if ( !is_wp_error( $post_id ) && $post_id > 0 ) {
            // 使用正确的帖子ID更新自定义字段
            update_post_meta( $post_id, '_quotation_date', sanitize_text_field($remainingRow[1]) );
        } else {
            // 可选:处理帖子创建失败的情况
            error_log('Failed to create post: ' . (is_wp_error($post_id) ? $post_id->get_error_message() : 'Invalid post ID'));
        }
    }
    
    fclose($fp);
    wp_send_json(array(
        'message' => __( 'Quotation added', 'gd-povestea-mea' )
    ));
    wp_die();
}

额外注意事项

  • 我注意到你用$remainingRow[0]同时设置了标题和内容,如果这不是你的本意,请记得修正对应的列索引。
  • 确保CSV文件的第二列(索引1)确实是你要导入的日期数据,列顺序要和代码里的索引对应。
  • 新增的错误处理逻辑能帮你排查文件上传、CSV读取、帖子创建等环节的问题,方便后续调试。
  • 确认自定义字段的键_quotation_date是正确的——如果是通过ACF这类插件创建的字段,有些键会带有特殊前缀,要和实际配置一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 20:44:06