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

如何在短代码中使用ACF Form并实现提交成功提示?

解决ACF短代码表单提交后的成功提示与重定向问题

核心问题分析

你直接在短代码函数中调用acf_form_head()是错误的——这个函数需要在WordPress发送HTTP头之前执行,而短代码是在页面内容渲染阶段才运行,此时HTTP头已经发送,这就是你遇到"cannot modify header information"错误的根本原因。同时ACF的默认提示机制需要正确的钩子配合才能生效。

解决方案步骤

1. 调整acf_form_head()的加载时机

移除短代码函数里的acf_form_head(),改用template_redirect钩子加载,确保在页面输出前执行:

add_action('template_redirect', function() {
    // 仅在包含表单的页面加载ACF表单头,替换为你的表单页面slug或ID
    if (is_page('你的表单页面slug')) {
        acf_form_head();
    }
});

2. 修复短代码函数,配置正确的成功提示

更新短代码函数,修正转义问题并添加成功提示参数:

function toyw_gallery_item_form_handler() {
    // 手动检测提交状态并显示提示(兼容ACF默认提示失效场景)
    if (isset($_GET['submitted']) && $_GET['submitted'] === 'true') {
        echo '<div id="message" class="updated"><p>投稿已提交,等待审核!</p></div>';
    }

    ob_start();

    $settings = array(
        'id' => 'gallery_form',
        'post_id' => 'new_post',
        'post_title' => false,
        'new_post' => array('post_type' => 'gallery-item', 'post_status' => 'pending'),
        'field_groups' => array('group_66acdfbecde2d'),
        'submit_value' => __('提交', 'acf'),
        'form_attributes' => array('class' => 'gallery_form'),
        'html_submit_button'  => '<input type="submit" class="acf-button button kb-button kt-button kt-btn-size-standard kt-btn-width-type-auto kb-btn-global-inherit" value="%s" />',
        // ACF默认成功提示配置
        'updated_message' => __('投稿已提交,等待审核!', 'acf'),
        'html_updated_message' => '<div id="message" class="updated"><p>%s</p></div>',
        // 提交后返回原页面并携带状态参数
        'return' => add_query_arg('submitted', 'true', get_permalink()),
    );

    acf_form($settings);
    
    return ob_get_clean();
}
add_shortcode('gallery_item_form', 'toyw_gallery_item_form_handler');

3. 正确实现重定向(替代返回原页面)

如果需要跳转到指定成功页面,使用acf/save_post钩子并终止脚本执行:

add_action('acf/save_post', 'toyw_acf_form_redirect', 1);
function toyw_acf_form_redirect($post_id) {
    // 仅针对表单提交的文章类型
    if (get_post_type($post_id) === 'gallery-item') {
        // 替换为你的成功页面URL
        wp_safe_redirect(get_permalink(get_page_by_path('投稿成功页面')));
        exit;
    }
}

关键注意事项

  • acf_form_head()必须在页面输出前加载,避免全局加载影响其他页面性能。
  • 短代码中的HTML属性无需额外转义双引号,PHP字符串用单引号包裹时内部双引号可直接使用。
  • 重定向时必须调用exit或die()终止脚本,防止后续输出触发header错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:22:39