How can I prevent form resubmission in WordPress?
I have a custom page with a form:
<?php
/*
Template Name: Submission
*/
get_header(); ?>
<!-- page article -->
<?php
// Include the page nav.
get_template_part( 'nav-page', 'nav' );
?>
<!-- container -->
<div class="container">
<!-- item -->
<div class="col-md-4">
<!-- content -->
<div class="multimedia-submission-text-block">
<?php
// Start the loop.
while ( have_posts() ) : the_post();
// Include the page content template.
get_template_part( 'content-page-article-submission', 'page psubmission' );
// End the loop.
endwhile;
?>
</div>
<!-- content -->
</div>
<!-- item -->
<!-- form -->
<div class="col-md-8">
<?php
// Set default variables.
$anon_submission_name = '';
$anon_submission_email = '';
$anon_submission_biography = '';
$success = false;
$error = false;
if (
isset($_POST['anon_submission_form_create_post_submitted'])
&& wp_verify_nonce($_POST['anon_submission_form_create_post_submitted'],'anon_submission_form_create_post')
) {
$anon_submission_name = trim($_POST['anon_submission_name']);
$anon_submission_email = trim($_POST['anon_submission_email']);
$anon_submission_biography = trim($_POST['anon_submission_biography']);
if ($anon_submission_title != ''
&& $anon_submission_name != ''
&& $anon_submission_email != ''
&& $anon_submission_biography != ''
) {
// post_author Take (int) The ID of the user who added the post. Default is the current user ID
$post_data = array(
'post_title' => $anon_submission_title,
// 'post_content' => $anon_submission_description,
'post_status' => 'pending',
'post_author' => 1, // admin user id
'post_type' => 'post'
);
// Insert the post and get its id.
$post_id = wp_insert_post($post_data);
if($post_id){
// Save other info in meta.
update_post_meta($post_id,'anon_submission_meta_name', $anon_submission_name);
update_post_meta($post_id,'anon_submission_meta_email', $anon_submission_email);
update_post_meta($post_id,'anon_submission_meta_biography', $anon_submission_biography);
$success = true;
echo '<p class="alert alert-success"><span class="close" data-dismiss="alert">×</span> Work submitted and awaiting moderation. Thank you for your submission.</p>';
}
} else { // author or text field is empty
$error = true;
echo '<p class="alert alert-danger"><span class="close" data-dismiss="alert">×</span> Work NOT submitted! Please correct the error(s) below.</p>';
}
}
?>
<form class="form-submission" method="post" action="<?php echo $current_url . '?' . mt_rand(1, 1000); ?>">
<?php wp_nonce_field('anon_submission_form_create_post', 'anon_submission_form_create_post_submitted'); ?>
<div class="row">
<!-- item -->
<div class="col-md-6">
<div class="form-group<?php if ($error && empty($anon_submission_name)): ?> has-error<?php endif; ?>">
<label for="inputName">Name (required)</label>
<input type="text" class="form-control" id="input-name" placeholder="Name" name="anon_submission_name" value="<?php if ($error) echo $anon_submission_name; ?>">
</div>
<div class="form-group<?php if ($error && empty($anon_submission_email)): ?> has-error<?php endif; ?>">
<label for="inputEmail">Email Address (required)</label>
<input type="email" class="form-control" id="input-email" placeholder="Email" name="anon_submission_email" value="<?php if ($error) echo $anon_submission_email; ?>">
</div>
<div class="form-group<?php if ($error && empty($anon_submission_biography)): ?> has-error<?php endif; ?>">
<label for="inputMessage">Biography (required)</label>
<textarea class="form-control" rows="6" placeholder="Biography" name="anon_submission_biography"><?php if ($error) echo $anon_submission_biography; ?></textarea>
</div>
</div>
<!-- item -->
</div>
<button type="submit" class="btn btn-default no-gradient">Submit</button>
</form>
</div>
<!-- form -->
</div>
<!-- container -->
<?php get_footer(); ?>
You always get a pop up of 'Confirm Form Resubmission' when you click the refresh button whether you have provided the info for all the required fields or not.
Any ideas?
EDIT:
Redirect:
...
} else { // author or text field is empty
wp_redirect( home_url() );
}
error:
Warning: Cannot modify header information - headers already sent by
(output started at /var/www/project-path/wp-includes/embed.php:363) in
/var/www/project-path/wp-includes/pluggable.php on line 1167
Don't write your actions in your template file. Write your actions in theme's functions.php
add_action('init','your_function_name');
function your_function_name(){
if($_POST['your_var']){
//...... do what ever
// then if neeeded do wp_redirect
}
}
Hope this resolves your problem.
A quick solution:
I put the processing code:
<?php
// Set default variables.
$anon_submission_name = '';
$anon_submission_email = '';
$anon_submission_biography = '';
$success = false;
$error = false;
....
Before:
<?php
/*
Template Name: Submission
*/
get_header(); ?>
And then redirect after validating and sending the form:
// Redirect to prevent form resubmission.
wp_redirect(get_permalink($post->ID) . '?success=true');
Related
I am looking for a approach to add multiple images option under the Feature image section in wordPress custom post type. I will integrate/implement these images on single.php file where I want to show the slider images. I want to do it using Codex / coding approach, Please NO PLUGIN. Any Idea/help will be appreciated.
EDIT
I have found this code and it has to be pasted in function.php or plugin.php. I have create a new file plug-slider.php and add the below code there & its not working, but the issue is that I have to call each image separately instead like create an array and call the array, also if there is no second/third image set for other post then the slider block is showing empty.. I don't know why, may be I am missing something... can someone please review.
Code Reference: Stack overflow question
//init the meta box
add_action( 'after_setup_theme', 'custom_postimage_setup' );
function custom_postimage_setup(){
add_action( 'add_meta_boxes', 'custom_postimage_meta_box' );
add_action( 'save_post', 'custom_postimage_meta_box_save' );
}
function custom_postimage_meta_box(){
//on which post types should the box appear?
$post_types = array('portfolios','page');
foreach($post_types as $pt){
add_meta_box('custom_postimage_meta_box',__( 'More Featured Images', 'yourdomain'),'custom_postimage_meta_box_func',$pt,'side','low');
}
}
function custom_postimage_meta_box_func($post){
//an array with all the images (ba meta key). The same array has to be in custom_postimage_meta_box_save($post_id) as well.
$meta_keys = array('second_featured_image','third_featured_image');
foreach($meta_keys as $meta_key){
$image_meta_val=get_post_meta( $post->ID, $meta_key, true);
?>
<div class="custom_postimage_wrapper" id="<?php echo $meta_key; ?>_wrapper" style="margin-bottom:20px;">
<img src="<?php echo ($image_meta_val!=''?wp_get_attachment_image_src( $image_meta_val)[0]:''); ?>" style="width:100%;display: <?php echo ($image_meta_val!=''?'block':'none'); ?>" alt="">
<a class="addimage button" onclick="custom_postimage_add_image('<?php echo $meta_key; ?>');"><?php _e('add image','yourdomain'); ?></a><br>
<a class="removeimage" style="color:#a00;cursor:pointer;display: <?php echo ($image_meta_val!=''?'block':'none'); ?>" onclick="custom_postimage_remove_image('<?php echo $meta_key; ?>');"><?php _e('remove image','yourdomain'); ?></a>
<input type="hidden" name="<?php echo $meta_key; ?>" id="<?php echo $meta_key; ?>" value="<?php echo $image_meta_val; ?>" />
</div>
<?php } ?>
<script>
function custom_postimage_add_image(key){
var $wrapper = jQuery('#'+key+'_wrapper');
custom_postimage_uploader = wp.media.frames.file_frame = wp.media({
title: '<?php _e('select image','yourdomain'); ?>',
button: {
text: '<?php _e('select image','yourdomain'); ?>'
},
multiple: false
});
custom_postimage_uploader.on('select', function() {
var attachment = custom_postimage_uploader.state().get('selection').first().toJSON();
var img_url = attachment['url'];
var img_id = attachment['id'];
$wrapper.find('input#'+key).val(img_id);
$wrapper.find('img').attr('src',img_url);
$wrapper.find('img').show();
$wrapper.find('a.removeimage').show();
});
custom_postimage_uploader.on('open', function(){
var selection = custom_postimage_uploader.state().get('selection');
var selected = $wrapper.find('input#'+key).val();
if(selected){
selection.add(wp.media.attachment(selected));
}
});
custom_postimage_uploader.open();
return false;
}
function custom_postimage_remove_image(key){
var $wrapper = jQuery('#'+key+'_wrapper');
$wrapper.find('input#'+key).val('');
$wrapper.find('img').hide();
$wrapper.find('a.removeimage').hide();
return false;
}
</script>
<?php
wp_nonce_field( 'custom_postimage_meta_box', 'custom_postimage_meta_box_nonce' );
}
function custom_postimage_meta_box_save($post_id){
if ( ! current_user_can( 'edit_posts', $post_id ) ){ return 'not permitted'; }
if (isset( $_POST['custom_postimage_meta_box_nonce'] ) && wp_verify_nonce($_POST['custom_postimage_meta_box_nonce'],'custom_postimage_meta_box' )){
//same array as in custom_postimage_meta_box_func($post)
$meta_keys = array('second_featured_image','third_featured_image');
foreach($meta_keys as $meta_key){
if(isset($_POST[$meta_key]) && intval($_POST[$meta_key])!=''){
update_post_meta( $post_id, $meta_key, intval($_POST[$meta_key]));
}else{
update_post_meta( $post_id, $meta_key, '');
}
}
}
}
My Callback code in single.php
<div class="project-carousel owl-carousel js-project-carousel">
<?php
while(have_posts()) {
the_post(); ?>
<!-- <div class="project-detail-item">
<?php //the_post_thumbnail('portfolio-slider') ?>
</div> -->
<?php
$slider_img=wp_get_attachment_image(get_post_meta(get_the_ID(),'second_featured_image', true),'full');
if($slider_img !='')
{?>
<div class="project-detail-item">
<?php
echo wp_get_attachment_image(get_post_meta(get_the_ID(),'second_featured_image', true),'full');
?>
</div>
<?php }
else
{
the_post_thumbnail('portfolio-slider');
}
?>
</div>
again the if/else block works for the empty check but only for single instance, like I have to check for each image... or I messed up?
Please do the below change and then try...
in your plugin file change this line.
$meta_keys = array('second_featured_image','third_featured_image');
To
$meta_keys = array('second_featured_image','third_featured_image','fourth_featured_image','fifth_featured_image');
change your call back single.php file code to something like below. Loop through each file and check for empty.
I have modified the code to accept up to 5/6 images so you can use it in the slider.
<div class="project-carousel owl-carousel js-project-carousel">
<?php
while(have_posts()) {
the_post();
$slider_img=the_post_thumbnail('portfolio-slider');
$slider_img1=wp_get_attachment_image(get_post_meta(get_the_ID(),'second_featured_image', true),'full');
$slider_img2=wp_get_attachment_image(get_post_meta(get_the_ID(),'third_featured_image', true),'full');
$slider_img3=wp_get_attachment_image(get_post_meta(get_the_ID(),'fourth_featured_image', true),'full');
$slider_img4=wp_get_attachment_image(get_post_meta(get_the_ID(),'fifth_featured_image', true),'full');
$slider_img5=wp_get_attachment_image(get_post_meta(get_the_ID(),'six_featured_image', true),'full');
$slider_img6=wp_get_attachment_image(get_post_meta(get_the_ID(),'svn_featured_image', true),'full');
if($slider_img !='')
{?>
<div class="project-detail-item">
<?php echo $slider_img;?>
</div>
<?php }?>
<?php if($slider_img1 !=''){ ?>
<div class="project-detail-item">
<?php echo $slider_img1; ?>
</div>
<?php }?>
<?php if($slider_img2 !=''){ ?>
<div class="project-detail-item">
<?php echo $slider_img2; ?>
</div>
<?php }?>
<!--image-->
<?php if($slider_img3 !=''){ ?>
<div class="project-detail-item">
<?php echo $slider_img3; ?>
</div>
<?php }?>
<!--image end-->
<!--image-->
<?php if($slider_img4 !=''){ ?>
<div class="project-detail-item">
<?php echo $slider_img4; ?>
</div>
<?php }?>
<!--image end-->
<!--image-->
<?php if($slider_img5 !=''){ ?>
<div class="project-detail-item">
<?php echo $slider_img5; ?>
</div>
<?php }?>
<!--image end-->
<!--image-->
<?php if($slider_img6 !=''){ ?>
<div class="project-detail-item">
<?php echo $slider_img6; ?>
</div>
<?php }?>
<!--image end-->
</div>
I'm working with a child theme and before the Gutenburg project was released, my page/form was working.
The page would post to itself and if the criteria was all met, it'd hide the form and display a success message. Now you have to click the submit button, the form's opacity changes (best way I can describe it) but then the form comes back. The form fields are still populated so I click submit again and then the form will post. But now I no longer see the success (or error) message any more.
<?php
$response = "";
//response messages
$not_human = "Please confirm you are human by clicking on the reCAPTCHA box.";
$bad_date_range = "The start date cannot be later than the end date. Please review your dates and submit again.";
$missing_content = "Please provide all information being asked. Your name, phone number, and email address will only be used internally and will not be visible by the public.";
$email_invalid = "Please review your email. It does not appear to be formatted correctly.";
//user posted variables
$firstname = strip_tags( stripslashes( $_POST['message_firstname'] ) );
$lastname = strip_tags( stripslashes( $_POST['message_lastname'] ) );
$email = strip_tags( stripslashes( $_POST['message_email'] ) );
$phone = strip_tags( stripslashes( $_POST['message_phone'] ) );
//function to generate response
function generate_response($type, $message){
global $response;
var_dump($type);
if($type == "success") {
$response = $message;
?>
<style>
.hpwd_gs_success {display: block !important;};
</style>
<?php
} else {
$response = $message;
?>
<style>
.hpwd_gs_error {display: block !important;};
</style>
<?php
}
}
function insertGSApplication( $firstname, $lastname, $email, $phone ) {
global $wpdb;
$my_table_name = $wpdb->prefix . 'my_junk';
$my_form_data = array(
'event_desc' => '<strong>Office Use Only:</strong><br/>' . $firstname . ' ' . $lastname . '<br/>' . $email . '<br/>' . $phone );
$wpdb->insert( $my_table_name, $my_form_data, array(
'%s',
'%s',
'%s',
'%s'
));
$event_id = $wpdb->insert_id;
__insertGSApplication($event_id, $begin, $end);
}
function __insertGSApplication($event_id, $begin, $end) {
global $wpdb;
$my_table_name = $wpdb->prefix . 'my_junk_events';
$group_id = 0;
$format = array( '%d', '%s', '%s', '%d' );
$data = array(
'occur_group_id' => $group_id
);
$result = $wpdb->insert( $my_table_name, $data, $format );
}
if(
isset($_POST['submit']) &&
!empty($_POST['submit'])
) {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
generate_response("error", $email . " " . $email_invalid); // email validation failed
}
else {
//validate presence of form fields **** need to also check for date and times; baby steps
if(
empty($firstname) ||
empty($lastname) ||
empty($phone)
){
generate_response("error", $missing_content); // missing some form data
} else if(empty($reCAPTCHA)) {
generate_response("error", $not_human); // missing captcha
} else if($startdate_alt > $enddate_alt) { // enddate is before start date
generate_response("error", $bad_date_range);
} else {
// human check (captcha start)
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$reCAPTCHA);
$responseData = json_decode($verifyResponse); // human check (captcha end)
if($responseData->success) { // validating google's response on human check
// save data
insertGSApplication( $firstname, $lastname, $email, $phone );
//send email per SendGrid documentation
$subject = 'GS Permit Application from ' . $firstname . ' ' . $lastname;
$message = $firstname . " " . $lastname . " has submitted a GS appliction for:";
$message .= "\r\n\r\n";
$message .= $address;
$message .= "\r\n\r\n";
$message .= "Go to " . get_site_url() . "/wp-admin/admin.php?page=my-junk-manage&limit=reserved&sort=4&order=ASC to approve it";
$to = array('gs#domain.com');
$headers = new SendGrid\Email();
$headers->setFromName("NO REPLY")
->setFrom("NOREPLY#domain.com")
->setBcc("other#domain.com")
->addCategory('GS');
$mail = wp_mail($to, $subject, $message, $headers);
// generate the reponse
generate_response("success",$message_saved);
} else {
generate_response("error",$message_unsaved);
}
}
}
}
get_header();
?>
<div id="main-content">
<div class="container">
<div id="content-area" class="clearfix">
<div id="left-area">
<h1 class="entry-title main_title"><?php the_title(); ?></h1>
<div class="entry-content">
<div id="hpwd_row" class="et_pb_section et_pb_section_1 et_section_regular">
<div class=" et_pb_row et_pb_row_1">
<div class="et_pb_column et_pb_column_4_4 et_pb_column_1 et-last-child">
<div class="et_pb_code et_pb_module et_pb_code_0">
<div class="et_pb_code_inner">
<div id="formid" class="et_pb_module et_pb_contact_form_container clearfix et_pb_contact_form_0" data-form_unique_num="0">
<div class="et_pb_contact">
<form id="hpwd_gs_frm" class="et_pb_contact_form clearfix" method="post" action="<?php get_site_url() ?>" autocomplete="false">
<p class="et_pb_contact_field et_pb_contact_field_0 et_pb_contact_field_half" data-id="name" data-type="input" style="">
<label for="message_firstname" class="et_pb_contact_form_label">First Name</label>
<input type="text" id="message_firstname" class="input" value="<?php echo $_POST['message_firstname']; ?>" name="message_firstname" data-required_mark="required" data-field_type="input" data-original_id="name" placeholder="First Name">
</p>
<p class="et_pb_contact_field et_pb_contact_field_1 et_pb_contact_field_half et_pb_contact_field_last" data-id="lastname" data-type="input" style="">
<label for="message_lastname" class="et_pb_contact_form_label">Last Name</label>
<input type="text" id="message_lastname" class="input" value="<?php echo $_POST['message_lastname']; ?>" name="message_lastname" data-required_mark="required" data-field_type="input" data-original_id="lastname" placeholder="Last Name">
</p>
<p class="et_pb_contact_field et_pb_contact_field_3 et_pb_contact_field_half" data-id="telephoneno" data-type="input" style="">
<label for="phone_us" class="et_pb_contact_form_label">Phone Numer</label>
<input type="text" class="phone_us" id="phone_us" value="<?php echo $_POST['message_phone']; ?>" name="message_phone" maxlength="14" placeholder="(999) 999-9999">
</p>
<p align="center">
<div align="center"><button type="submit" name="submit" value="I have read and agree to the terms and conditions above" class="et_pb_contact_submit et_pb_button">I have read and agree to the terms and conditions above</button></div>
</p>
<p align="center"> </p>
<input type="hidden" id="_wpnonce-et-pb-contact-form-submitted" name="_wpnonce-et-pb-contact-form-submitted" value="e089401553"><input type="hidden" name="_wp_http_referer" value="/domain/contact-us-today/">
</form>
</div> <!-- .et_pb_code_inner -->
</div>
</div> <!-- .et_pb_code_inner -->
</div> <!-- .et_pb_code -->
</div> <!-- .et_pb_column -->
</div>
</div>
</div>
</div> <!-- #left-area -->
<?php get_sidebar(); ?>
</div> <!-- #content-area -->
</div> <!-- .container -->
</div> <!-- #main-content -->
<?php get_footer(); ?>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<!-- <link rel="stylesheet" type="text/css" media="all" href="/sandimas/assets/daterangepicker/daterangepicker.css" /> -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> -->
This is my first time to create a form without the use of a plugin - couldn't find a plugin that would do what I need so this approach was taken.
WordPress nonce had some bad syntax.
I have create custom wordpress login with validation but there is a problem once submit the email and the password no validation shows even with success or error i'm trying to build custom user auth i have created register and reset password the rest which is login and profile page under developing so i have created all needed redirection to allow my custom pages to take place of the wordpress default pages so i need to know what's wrong with my code and how to redirect after login to custom page here is my code
<?php
global $wpdb;
$error = '';
$success = '';
// check if we're in login form
if( isset( $_POST['action'] ) && 'login' == $_POST['action'] )
{
$email = trim($_POST['log']);
$password = trim($_POST['pwd']);
if( empty( $email ) || empty( $password ) ) {
$error = 'Enter a username or e-mail address..';
} else if( ! password_exists( $password ) ) {
$error = 'password is incorrect.';
} else if( ! is_email( $email )) {
$error = 'Invalid username or e-mail address.';
} else if( ! email_exists( $email ) ) {
$error = 'There is no user registered with that email address.';
} else {
if( email_exists( $email ) ) {
$success = 'successfully loged in.';
} else {
$error = 'Oops something went wrong while loging in to your account.';
}
}
if( ! empty( $error ) )
echo 'error text';
if( ! empty( $success ) )
echo 'error text';
}
<!-- Show logged out message if user just logged out -->
<?php if ( $attributes['logged_out'] ) : ?>
<p class="login-info">
<?php _e( 'You have signed out. Would you like to sign in again?', 'personalize-login' ); ?>
</p>
<?php endif; ?>
<?php if ( $attributes['registered'] ) : ?>
<p class="login-info">
<?php
printf(
__( 'You have successfully registered to <strong>%s</strong>. We have emailed your password to the email address you entered.', 'personalize-login' ),
get_bloginfo( 'name' )
);
?>
</p>
<?php endif; ?>
<?php if ( $attributes['lost_password_sent'] ) : ?>
<p class="login-info">
<?php _e( 'Check your email for a link to reset your password.', 'personalize-login' ); ?>
</p>
<?php endif; ?>
<?php if ( $attributes['password_updated'] ) : ?>
<p class="login-info">
<?php _e( 'Your password has been changed. You can sign in now.', 'personalize-login' ); ?>
</p>
<?php endif; ?>
<!-- START Login Form -->
<form id="form-login" class="p-t-15" action="<?php echo wp_login_url(); ?>">
<!-- START Form Control-->
<div class="form-group form-group-default">
<label>Login</label>
<div class="controls">
<?php $user_login = isset( $_POST['user_login'] ) ? $_POST['user_login'] : ''; ?>
<input type="text" name="log" id="user_login" placeholder="User Name" class="form-control" required>
</div>
</div>
<!-- END Form Control-->
<!-- START Form Control-->
<div class="form-group form-group-default">
<label>Password</label>
<div class="controls">
<?php $user_pass = isset( $_POST['user_pass'] ) ? $_POST['user_pass'] : ''; ?>
<input type="password" class="form-control" name="pwd" id="user_pass" placeholder="Credentials" required>
</div>
</div>
<!-- START Form Control-->
<div class="row">
<div class="col-md-6 no-padding sm-p-l-10">
<div class="checkbox ">
<input type="checkbox" value="1" id="checkbox1">
<label for="checkbox1">Keep Me Signed in</label>
</div>
</div>
<div class="col-md-6 d-flex align-items-center justify-content-end">
Help? Contact Support
</div>
</div>
<!-- END Form Control-->
<button class="btn btn-primary btn-cons m-t-10" type="submit">Sign in</button>
</form>
<!--END Login Form-->
Form elements are passed by name, not by id, i.e. in your case you will need to get $_GET['log'] for the user name, not $_GET['user_login'].
However: There are many problems with this code. You shouldn't pass private info via GET, shouldn't tell the user whether a login error involves the user name or the password, etc. If you rewrite this code with best practices in mind, it will be easier to find problems with the functional flow.
How can I add my ACF field into another plugin's form?
I tried this but this does not work
<div class="input-group">
<label for="deal_title"><?php _e('Deal title', 'wcd'); ?> <span class="required">*</span></label>
<input type="text" name="deal_title" id="deal_title" value="<?php echo esc_attr($deal_title) ?>" class="form-control" data-validation="required" data-error="<?php esc_attr_e('Please input deal description', 'wcd'); ?>">
<p class="description"><?php _e('Input title for the deal.', 'wcd'); ?></p>
</div>
//This is the part I want my ACF field
<?php echo the_field('business_name'); ?>
<div class="input-group">
<label for="deal_description" data-error="<?php esc_attr_e('Please type description of the deal', 'wcd'); ?>"><?php _e('Deal Description', 'wcd'); ?> <span class="required">*</span></label>
<?php wp_editor($deal_description, 'deal_description'); ?>
<p class="description"><?php _e('Input description of the deal.', 'wcd'); ?></p>
</div>
How will this be achieved?
Create a new template and assign that to a page..
Now in that template copy this code :
You have to change 2 things in below code 1. YOUR_POST_TYPE , 2. YOUR
FIELD GROUP
Field group can be achieved by editing any field group (its ID will be in the top).
<?php acf_form_head(); ?>
<?php get_header(); ?>
<?php
function my_pre_save_post( $post_id )
{
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
// Create a new post
$post = array(
'post_status' => 'publish' ,
'post_title' => $_POST['fields']['title'] ,
'post_type' => 'YOUR_POST_TYPE' ,
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
?>
<div id="content" class="clearfix row">
<div id="main" class="col-sm-12 clearfix" role="main">
<?php
acf_form(array(
'field_groups' => array('YOUR FIELD GROUP'),
'post_id' => 'new',
'submit_value' => 'Submit Product'
)); ?>
</div> <!-- end #main -->
<?php //get_sidebar(); // sidebar 1 ?>
</div> <!-- end #content -->
<?php get_footer(); ?>
I try to create a plugin allow users to add new post, edit post, and delete post from the front end.
Now when the user try to edit the post instead of updating the the same post the plugin create new page ! in pending status.
Can anyone help me please?
This is the code of edit post class:
<?php
/**
* Edit Post form class
*
* #author Engr.MTH
* #package MOSTASHAROON Frontend Form
*/
class MOSFF_Edit_Post {
function __construct() {
add_shortcode( 'mosff_editpost', array($this, 'shortcode') );
}
/**
* Handles the edit post shortcode
*
*
*/
function shortcode() {
$query = new WP_Query(array('post_type' => 'post', 'posts_per_page' =>'-1', 'post_status' => array('publish', 'pending', 'draft', 'private', 'trash') ) );
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();global $post;
if(isset($_GET['post'])) {
if($_GET['post'] == $post->ID)
{
$current_post = $post->ID;
$title = get_the_title();
$content = get_the_content();
$custom_one = get_post_meta($current_post, 'vsip_custom_one', true);
$custom_two = get_post_meta($current_post, 'vsip_custom_two', true);
}
}
endwhile; endif;
wp_reset_query();
global $current_post;
$postTitleError = '';
if(isset($_POST['submitted']) && isset($_POST['post_nonce_field']) && wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) {
if(trim($_POST['postTitle']) === '') {
$postTitleError = 'Please enter a title.';
$hasError = true;
} else {
$postTitle = trim($_POST['postTitle']);
}
$post_information = array(
'ID' => $current_post,
'post_title' => esc_attr(strip_tags($_POST['postTitle'])),
'post_content' => esc_attr(strip_tags($_POST['postContent'])),
'post-type' => 'post',
'post_status' => 'pending'
);
$post_id = wp_update_post($post_information);
if($post_id)
{
// Update Custom Meta
update_post_meta($post_id, 'vsip_custom_one', esc_attr(strip_tags($_POST['customMetaOne'])));
update_post_meta($post_id, 'vsip_custom_two', esc_attr(strip_tags($_POST['customMetaTwo'])));
wp_redirect( home_url() ); exit;
}
}
?>
<!-- #primary BEGIN -->
<div id="primary">
<form action="" id="primaryPostForm" method="POST">
<fieldset>
<label for="postTitle"><?php _e('Post\'s Title:', 'framework') ?></label>
<input type="text" name="postTitle" id="postTitle" value="<?php echo $title; ?>" class="required" />
</fieldset>
<?php if($postTitleError != '') { ?>
<span class="error"><?php echo $postTitleError; ?></span>
<div class="clearfix"></div>
<?php } ?>
<fieldset>
<label for="postContent"><?php _e('Post\'s Content:', 'framework') ?></label>
<textarea name="postContent" id="postContent" rows="8" cols="30"><?php echo $content; ?></textarea>
</fieldset>
<fieldset>
<label for="customMetaOne"><?php _e('Custom Meta One:', 'framework') ?></label>
<input type="text" name="customMetaOne" id="customMetaOne" value="<?php echo $custom_one; ?>" />
</fieldset>
<fieldset>
<label for="customMetaTwo"><?php _e('Custom Meta Two:', 'framework') ?></label>
<input type="text" name="customMetaTwo" id="customMetaTwo" value="<?php echo $custom_two; ?>" />
</fieldset>
<fieldset>
<?php wp_nonce_field('post_nonce', 'post_nonce_field'); ?>
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit"><?php _e('Update Post', 'framework') ?></button>
</fieldset>
</form>
</div><!-- #primary END -->
<?php }}
$mosff_editpostform = new MOSFF_Edit_Post();
I found the answer, just I remove this line:
global $current_post;
I think you can do this by getting the post id and query it to get all the fields of the particular and edit it through a form and post it again.
get more detailed article herekvcodes.