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

如何获取CF7上传至WordPress媒体库的图片文件名/URL?

解决方案:获取Tablesome存入媒体库的CF7上传图片并保存到CPT

因为文件是Tablesome插件负责从CF7临时目录移至媒体库并重命名的,所以不能用CF7的钩子(这些钩子触发时文件还未被处理),需要借助Tablesome的提交后钩子来操作。

步骤1:使用Tablesome的提交完成钩子

Tablesome提供了tablesome_after_save_submission钩子,会在提交数据(包括上传文件存入媒体库)完成后触发,此时可以安全获取媒体库中的图片信息。

步骤2:编写自定义代码

将以下代码添加到主题的functions.php文件或自定义插件中,根据你的实际情况替换对应参数:

add_action('tablesome_after_save_submission', 'sync_cf7_upload_to_cpt', 10, 3);
function sync_cf7_upload_to_cpt($submission_id, $form_id, $entry) {
    // 1. 指定目标CF7表单ID(替换成你的表单ID)
    $target_form_id = 123;
    if ($form_id !== $target_form_id) return;

    // 2. 指定CF7上传字段的名称(比如你的字段是[file user_upload],这里填'user_upload')
    $upload_field_key = 'user_upload';
    if (!isset($entry[$upload_field_key])) return;

    // 3. 处理上传文件数据(兼容单文件/多文件上传)
    $upload_items = $entry[$upload_field_key];
    if (!is_array($upload_items)) $upload_items = [$upload_items];

    // 4. 创建CPT文章(替换成你的CPT slug)
    $cpt_post = [
        'post_type' => 'user_submission',
        'post_title' => '用户提交内容 - ' . date('Y-m-d H:i:s'),
        'post_status' => 'publish',
        'post_author' => get_current_user_id() ?: 1
    ];
    $post_id = wp_insert_post($cpt_post);
    if (!$post_id) return;

    // 5. 遍历上传文件,获取媒体库信息并更新ACF字段
    $acf_field_key = 'submitted_image'; // 替换成你的ACF字段键
    $attachment_ids = [];

    foreach ($upload_items as $item) {
        // 从Tablesome返回的条目里获取原始文件名,查找媒体库中的附件
        $original_name = $item['name'];
        $attachments = get_posts([
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'meta_query' => [
                ['key' => '_wp_attached_file', 'value' => $original_name, 'compare' => 'LIKE']
            ],
            'numberposts' => 1
        ]);

        if (!empty($attachments)) {
            $attachment = reset($attachments);
            $attachment_ids[] = $attachment->ID;
        }
    }

    // 6. 更新ACF字段(如果是单文件字段,用reset($attachment_ids);多文件直接传数组)
    update_field($acf_field_key, $attachment_ids, $post_id);
}

调试技巧

如果不确定$entry的结构,可以先添加调试代码查看数据:

add_action('tablesome_after_save_submission', 'debug_tablesome_entry_data', 10, 3);
function debug_tablesome_entry_data($submission_id, $form_id, $entry) {
    // 日志会输出到wp-content/debug.log(需开启WP_DEBUG)
    error_log('Tablesome Entry Data: ' . print_r($entry, true));
}

开启WP_DEBUG后,提交一次表单,查看日志里的上传字段数据,若Tablesome直接返回了媒体库附件ID,可直接使用,无需通过文件名查找。

注意事项

  • 确保Tablesome插件已开启CF7集成功能,且上传字段配置正确。
  • ACF字段需设置为图片字段(若存ID)或文本字段(若存URL),对应代码中的update_field参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 13:03:26