I’m using ACF Form in Front-end of a WordPress website. It is used to create a custom posts in WordPress. I need to add two submit buttons in this ACF Form. when i click the first button, it should create a new post and post status should be publish and when I click the another button, it should create a new post and post status should be draft.
My code below will create a post with status as published. How can i achieve this?
<?php acf_form(array( 'post_id' => 'new_post', 'field_groups' => array(258), 'new_post' => array( 'post_type' => 'property', ), 'post_title' => true, 'post_title_label' => 'Community Name', 'submit_value' => 'Submit for Review' )); ?>
Advertisement
Answer
It is possible achieve this using the hidden field and a bit of jQuery.
Step 1: You need to add the hidden field and set default value as 1.
<?php acf_form_head(); acf_form(array( 'post_id' => 'new_post', 'field_groups' => array(258), 'new_post' => array( 'post_type' => 'property', ), 'id' => 'form_draft', 'html_after_fields' => '<input type="hidden" id="hiddenId" name="acf[current_step]" value="1"/>', 'return' => home_url('property-thank-you'), 'post_title' => true, 'post_title_label' => 'Community Name', 'submit_value' => 'Publish' ) ); ?>
Step 2:
Use the below code near the form and then append this field to the form using jQuery.
<input type="submit" id="draft_btn" class="acf-button2 button button-primary button-large" name="draft_btn" value="Save as Draft" onclick="click_ignore();"> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery("#draft_btn").detach().appendTo('.acf-form-submit'); }); </script>
Step 3: When Clicking on the “Draft” button overwrite its value as 2.
<script type="text/javascript"> function click_ignore(e) { document.getElementById('hiddenId').value = 2; return false; } </script>
Step 4: Add the below code in fucntions.php which will change the post status based on the button which we click.
<?php function my_acf_save_post($post_id) { $submitedStatus = $_POST['acf']['current_step']; if ($submitedStatus == 1){ $value = 'pending'; }else if ($submitedStatus == 2){ $value = 'draft'; } // Update current post $my_post = array( 'ID' => $post_id, 'post_status' => $value, ); remove_action('acf/save_post', 'my_acf_save_post', 20); // Update the post into the database wp_update_post($my_post); // Add the action back add_action('acf/save_post', 'my_acf_save_post', 20); } // run after ACF saves the $_POST['acf'] data add_action('acf/save_post', 'my_acf_save_post', 20); ?>
We have added both the ‘Publish’ and ‘Save as Draft’ buttons in a single ACF form.