Search code examples
wordpressadvanced-custom-fields

ACF Front End Form Posting Twice


I've used ACF on the back end a good bit but I'm newer to using a front end ACF form. I have a fresh WP install for testing.

I have the form working but for some reason it is creating two duplicate records every time I submit the form. I can't find anything in the form that would submit it twice.

<?php
// Show ACF Form On Front End Via ShortCode

// Code to show form
add_action('init', 'brandpage_form_head');
function brandpage_form_head() {
    acf_form_head();
}

// Function for the shortcode
function bwp_acf_form_function($attr) {

    // If ACF isn't running then exit
    if (!function_exists('acf_form')) {
        return;
    }

    // Buffer data instead of outputting it
    ob_start();

    // Unique form ID to avoid conflicts
    $form_id = 'bwp-acf-form-' . uniqid();

    // Debug: Log form ID and request data
    error_log('Rendering ACF Form with ID: ' . $form_id);
    error_log('Request data: ' . print_r($_REQUEST, true));

    // Display ACF form
    acf_form(array(
        'id'               => $form_id,
        'post_id'          => 'new_post',
        'new_post'         => array(
            'post_type'   => 'daily-message',
            'post_status' => 'draft',
        ),
        'field_groups'     => array($attr['field_group_id']),
        'post_title'       => false, // False to auto-populate
        'post_content'     => false, // False to not use for content
        'submit_value'     => __("Update", 'acf'),
        'updated_message'  => __("Daily Messenger Post Added", 'acf'),
        'return'           => '', // Redirect URL after saving (empty string means no redirect)
        'html_after_fields'=> '<input type="hidden" name="my_form_nonce" value="' . wp_create_nonce('my_form_nonce_action') . '">', // Add nonce for security
    ));

    // Empty the buffer data
    return ob_get_clean();
}

// Add the shortcode
add_shortcode('bwp_acf_form', 'bwp_acf_form_function');

?>

Any ideas why this might be posting twice?


Solution

  • Finally found an answer on the ACF support forum and although I'm not 100% sure why it does work:

    Remove the init hook and try putting acf_form_head(); inside header.php

    This solved the problem.