wordpress insert post doesnt work on edge - php

I create a code to save data from Form to custom_post_type.
Everything ok on Firefox but when I test it on edge, the post still save, but I can't edit the post on admin, or view the post(object not found) (see the image)
I really don't know where is the problem, please help.
this is my code, i copy it from my function.php:
function wpshout_frontend_post() {
wpshout_save_post_if_submitted();
?>
<div>
<div>
RESERVATION
</div>
<form id="new_post" class = 'datcho' name="new_post" method="post">
<input type = 'text' name = 'ten' required>
<input type = 'tel' name = 'sdt' required>
<input type = 'number' name = 'num' min='1' max = '10' required>
<input type = 'date' name = 'ngay' required>
<input type = 'time' name = 'time' value = '13:00' min='9:00' max='21:00' required>
<?php wp_nonce_field( 'wps-frontend-post' ); ?>
<input type="submit" value="Reservation" id="submit" name="submit"/>
</div>
</form>
</div>
<?php
}
function wpshout_save_post_if_submitted() {
// Stop running function if form wasn't submitted
if ( !isset($_POST['ten']) ) {
return;
}
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'wps-frontend-post') ) {
echo 'Did not save because your form seemed to be invalid. Sorry';
return;
}
// Do some minor form validation to make sure there is content
// Add the content of the form to $post as an array
$title = wp_strip_all_tags($_POST['ten']);
$post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'Pending',
'post_type' => 'datcho'
);
$eror = wp_insert_post($post,true);
if($eror){
$sdt = wp_strip_all_tags($_POST['sdt']);
$ngay = wp_strip_all_tags($_POST['ngay']);
$time = wp_strip_all_tags($_POST['time']);
$num = wp_strip_all_tags($_POST['num']);
add_post_meta($eror, 'sdt', $sdt);
add_post_meta($eror, 'ngay', $ngay);
add_post_meta($eror, 'time', $time);
add_post_meta($eror, 'num', $num);
echo 'Saved your post successfully! :)';
}else {
echo "something wrong";
}
}

Here is the complete solution.
The issue mainly is you are not logged into the WP in Edge so when creating the post using wp_insert_post wordpress has no idea with which account should it attach that post.
function wpshout_frontend_post() {
wpshout_save_post_if_submitted();
?>
<div>
<div>
RESERVATION
</div>
<form id="new_post" class = 'datcho' name="new_post" method="post">
<input type = 'text' name = 'ten' required>
<input type = 'tel' name = 'sdt' required>
<input type = 'number' name = 'num' min='1' max = '10' required>
<input type = 'date' name = 'ngay' required>
<input type = 'time' name = 'time' value = '13:00' min='9:00' max='21:00' required>
<?php wp_nonce_field( 'wps-frontend-post' ); ?>
<input type="submit" value="Reservation" id="submit" name="submit"/>
</form>
</div>
<?php
}
function wpshout_save_post_if_submitted() {
// Stop running function if form wasn't submitted
if ( !isset($_POST['ten']) ) {
return;
}
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'wps-frontend-post') ) {
echo 'Did not save because your form seemed to be invalid. Sorry';
return;
}
// Do some minor form validation to make sure there is content
// Add the content of the form to $post as an array
$title = wp_strip_all_tags($_POST['ten']);
$author_id = 1; // You can change it with your User ID
$post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'draft',
'post_type' => 'datcho'
'post_author' => $author_id
);
$eror = wp_insert_post($post,true);
if($eror){
$sdt = wp_strip_all_tags($_POST['sdt']);
$ngay = wp_strip_all_tags($_POST['ngay']);
$time = wp_strip_all_tags($_POST['time']);
$num = wp_strip_all_tags($_POST['num']);
add_post_meta($eror, 'sdt', $sdt);
add_post_meta($eror, 'ngay', $ngay);
add_post_meta($eror, 'time', $time);
add_post_meta($eror, 'num', $num);
echo 'Saved your post successfully! :)';
}else {
echo "something wrong";
}
}

Related

How to use ajax to post wordpress comments?

i am building a wordpress theme and in that i have a custom contact form which stores data in a custom post type Messages when a user fills that form and submit it.
here is the code below
Contact-form.php
<form id="salmanlateefContactForm" class="salmanlateef-contact-form" action="#" method="post" data-url="<?php echo admin_url('admin-ajax.php'); ?>">
<div class="form-group">
<input type="text" class="form-control salmanlateef-form-control" placeholder="Your Name" id="name" name="name" required="required">
<small class="text-danger form-control-msg">Your Name Is Required</small>
</div>
<div class="form-group">
<input type="email" class="form-control salmanlateef-form-control" placeholder="Your Email" id="email" name="email" required="required">
<small class="text-danger form-control-msg">Your Email Is Required</small>
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control salmanlateef-form-control" required="required" placeholder="Your Message"></textarea>
<small class="text-danger form-control-msg">A Message Is Required</small>
</div>
<div class="text-center">
<button type="submit" class="btn btn-default btn-lg btn-salmanlateef-form">Submit</button>
<small class="text-info form-control-msg js-form-submission">Submission in process, please wait...</small>
<small class="text-success form-control-msg js-form-success">Message successfully submitted, thank you!</small>
<small class="text-danger form-control-msg js-form-error">There was an error while submitting the message, please try again</small>
</div>
JQuery
/* contact form submission */
$('#salmanlateefContactForm').on('submit', function(e){
e.preventDefault();
$('.has-error').removeClass('has-error');
$('.js-show-feedback').removeClass('js-show-feedback');
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
message = form.find('#message').val(),
ajaxurl = form.data('url');
if( name === '' ){
$('#name').parent('.form-group').addClass('has-error');
return;
}
if( email === '' ){
$('#email').parent('.form-group').addClass('has-error');
return;
}
if( message === '' ){
$('#message').parent('.form-group').addClass('has-error');
return;
}
form.find('input, button, textarea').attr('disabled', 'disabled');
$('.js-form-submission').addClass('js-show-feedback');
$.ajax({
url : ajaxurl,
type : 'post',
data : {
name : name,
email : email,
message : message,
action: 'salmanlateef_save_user_contact_form'
},
error : function( response ){
$('.js-form-submission').removeClass('js-show-feedback');
$('.js-form-error').addClass('js-show-feedback');
form.find('input, button, textarea').removeAttr('disabled');
},
success : function( response ){
if( response == 0 ){
setTimeout(function() {
$('.js-form-submission').removeClass('js-show-feedback');
$('.js-form-error').addClass('js-show-feedback');
form.find('input, button, textarea').removeAttr('disabled');
},1500);
} else {
setTimeout(function() {
$('.js-form-submission').removeClass('js-show-feedback');
$('.js-form-success').addClass('js-show-feedback');
form.find('input, button, textarea').removeAttr('disabled').val('');
},1500);
}
}
});
});
Ajax.php
add_action( 'wp_ajax_nopriv_salmanlateef_save_user_contact_form', 'salmanlateef_save_contact' );
add_action( 'wp_ajax_salmanlateef_save_user_contact_form', 'salmanlateef_save_contact' );
function salmanlateef_save_contact(){
$title = wp_strip_all_tags($_POST["name"]);
$email = wp_strip_all_tags($_POST["email"]);
$message = wp_strip_all_tags($_POST["message"]);
$args = array(
'post_title' => $title,
'post_content' => $message,
'post_author' => 1,
'post_status' => 'publish',
'post_type' => 'salmanlateef_contact',
'meta_input' => array(
'_contact_email_value_key' => $email
)
);
$postID = wp_insert_post( $args );
if ($postID !== 0) {
$to = get_bloginfo( 'admin_email' );
$subject = 'Salman Lateef Contact Form - '.$title;
$header[] = 'From: '.get_bloginfo( 'name' ).' <'.$to.'>';
$header[] = 'Reply-To: '.$title.' <'.$email.'>';
$header[] = 'Content-Type: text/html: charset=UTF-8';
wp_mail( $to, $subject, $message, $headers );
echo $postID;
} else {
echo 0;
}
die();
}
What i want is use the same logic to post comments to a post using comments form. Hope i am clear on the question. Looking forward for a reply. Thanks in advance
Since Version 2.8, The JavaScript global variable ajaxurl can be used in case you want to separate your JavaScript code from php files into JavaScript only files. This is true on the administration side only. If you are using AJAX on the front-end, you need to make your JavaScript aware of the admin-ajax.php url.
So please use admin-ajax rather than the ajaxurl in your theme.
$args = array(
'comment_author' => $author,
'comment_author_email' => $email,
'comment_content' => $comment,
'comment_parent' => $commentParent,
'comment_post_ID' => $postID,
'user_id' => $userID,
);
$commentID = wp_new_comment( $args );
if ($commentID !== 0) {
echo $commentID;
} else {
echo 0;
}
i used the wp_new_comment() function and it served my purpose. however i am still trying to figure out a way to append the newly generated comment into the comments list in the single.php

Codeigniter insert array into database

I am currently making a registration form where in you could register individually or by many I need a way how to make the multiple register work i cant add the input into db i get an array to string conversion error
i still dont have the model for this
my code is
controller
public function registerbatch(){
for ($i = 0; $i < count($this->input->post('surname','firstname','age','school','course','email')); $i++) {
$this->form_validation->set_rules("surname[$i]", "surname[$i]", "required");
$this->form_validation->set_rules("firstname[$i]", "firstname[$i]", "required");
$this->form_validation->set_rules("age[$i]", "Age[$i]", "required");
$this->form_validation->set_rules("school[$i]", "School[$i]", "required");
$this->form_validation->set_rules("course[$i]", "Course[$i]", "required");
$this->form_validation->set_rules("email[$i]", "Email[$i]", "required");
}
if ($this->form_validation->run() == TRUE) {
$reg_dat = array(
'surname' => $this->input->post('surname'),
'name' => $this->input->post('firstname'),
'age' => $this->input->post('age'),
'school' => $this->input->post('school'),
'course' => ($this->input->post('course')),
'email' => ($this->input->post('email')),
);
$this->user_model->add_user($reg_dat);
$this->load->view('user/home_view');
} else {
$this->load->view('user/batch_register');
}
view:
<html>
<head>
</head>
<body>
<form class="form" action="<?php echo base_url() . 'user/registerbatch'; ?>" method="post" class="form-horizontal" role="form">
<?php for ($i = 0; $i < $num; $i++): ?>
<br>
Surname: <input type="text" name="surname[]">
<br>
Name: <input type="text" name="firstname[]">
<br>
Age:<input type ="int" name ="age[]">
<br>
School: <input type="text" readonly value="<?= $school ?>" name="school[]">
<br>
Course:<input type ="text" name ="course[]">
<br>
Email:<input type ="text" name ="email[]">
<br>
<br>
<?php endfor ?>
<button type="submit" class="btn btn-success">Register</button>
</body>
</html>
Try this below coding ....
if ($this->form_validation->run() == TRUE) {
extract($_POST);
foreach($surname as $key=>$value) {
$reg_dat = array(
'surname' => $value,
'name' => $firstname[$key],
'age' => $age[$key],
'school' => $school[$key],
'course' => $course[$key],
'email' => $email[$key],
);
$this->user_model->add_user($reg_dat);
}
}
$this->load->view('user/home_view');
Seems that your Post can be a multidimensional array. I think the best way to solve your problem is to foreach that post and insert every row
//your controller
if ($this->form_validation->run() == TRUE) {
$reg_dat_multi = $this->input->post();
foreach ($reg_dat_multi as $reg_dat) {
$this->user_model->add_user($reg_dat);
}
);
you didn't show your model but let's think that is something like this
//your model
function add_user($reg_dat){
if ( $this->db->insert('table', $reg_dat) ){
return true;
}
return false;
}
hope that helps

Wordpress. How can I view and send get/post requests in php?

Wordpress. How an I view and send get/post requests in php?
This plugin's code is not working:
I wrote this plugin. it is all the source code.
Plugin's file index.php
this function could be start on the activate plugin:
function activate() {
// registration
$post = array(
//'ID' => 15, // Are you updating an existing post?
'post_content' => '
<form action="#" method="post">
<p>
<label for="username">username: </label>
<input type="text" id="username" /><br />
<label for="nick">password: </label>
<input type="text" id="password" /><br />
<label for="password_repeat">repeat_password: </label>
<input type="text" id="repeat_password" /><br />
<label for="email">Email: </label>
<input type="text" id="email" /><br />
<label for="age">Возраст </label>
<input type="text" id="age" /><br />
<input type="submit" value="Enter">
</p>
</form>
', // The full text of the post.
'post_name' => 'reg', // The name (slug) for your post
'post_title' => 'reg', // The title of your post.
'post_status' => 'publish', // Default 'draft'.
'post_type' => 'page', // Default 'post'.
);
$post_id = wp_insert_post( $post, $wp_error );
}
register_activation_hook( __FILE__, 'activate' );
function market () {
$user_login = $_POST['user_login'];
$user_pass = $_POST['user_pass'];
$test = "testesttest";
return $test;
}
//add_action( 'init', 'register_form' );
add_action( 'get_header', 'market' );
to view post and get requests you can use the debug bar plugin:
https://wordpress.org/plugins/debug-bar/
I need it in my php code:
function sitemarket () {
if ( 'POST' != $_SERVER['REQUEST_METHOD'] ) {
header('Allow: POST');
header('HTTP/1.1 405 Method Not Allowed');
header('Content-Type: text/plain');
exit;
}
nocache_headers();
var_dump($_POST);
$comment = isset($_POST['username']) ? $_POST['username'] : "";
var_dump($comment);
//$test = authentication("user123","user951");
$test = "testesttest";
return $test;
}
//add_action( 'init', 'register_form' );
add_action( 'get_header', 'sitemarket' );
Why POST REQUEST = NULL ?

Clear form after submit and page refresh - Wordpress

I know that the correct way to insert the data is using AJAX, but I don't mind if the page refreshes. Can anybody help me clear the form data after the page refreshes? Everything works fine, the data is being submitted to the table, and the page refreshes. But if I hit the refresh button again, it tells me that the data will be submitted ... and I don't know what to do.
<?php
$current_user = wp_get_current_user();
if ( $current_user->ID == 0 ) {
} else {
if( isset( $_POST['drop_artists'] ) ) {
$answer = $_POST['drop_artists'];
}else{
$answer = $_POST['artist_name'];
}
$date = current_time( 'mysql' );
$table = "t4t5_answers";
$sql = $wpdb->prepare( "INSERT INTO $table (user_id, post_id, info, answer, submission_date ) VALUES ( %d, %d, %s, %s, %d )", $current_user->ID, $post->ID, 'artist', $answer, $date );
$wpdb->query($sql);
header('Location: ' . get_bloginfo('url'));
}//if(isset($_POST['form_sub']))
?>
<form method="post" action="" id="artists-form">
<ul>
<li id="categories">
<?php
$args = array(
'show_option_all' => 'Artists',
'hierarchical' => 1,
'child_of' => 406,
'order_by' => 'name',
'name' => 'answer',
'hide_empty' => 0
);
wp_dropdown_categories($args); ?>
</li>
</ul>
<input type="text" name="artist_name" value="" size="45" id="input-title"/>
<input id="submitButton" class="subput" type="submit" name="submit" value="Add"/>
</form>
After the page is posted, use a redirect to send te user to a success page. This will make the page that was actually posted not appear in their history.
if (!empty($_POST)) {
// do stuff
header("Location: $_SERVER[PHP_SELF]");
}
Note the URL for the redirect should be a full URL, not a relative one. In practice though, I haven't seen any browsers have a problem with the relative URL.
To redirect to your current url immediately, try this one
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$current_URL.'">'
for more details see http://en.wikipedia.org/wiki/Meta_refresh
Write your php code inside if(isset($_POST['submit']) and add following script below insert statement.
echo " <script type='text/javascript'>
window.location=document.location.href;
</script>";
Your code will look like the following:
global $wpdb,$post;
if(isset($_POST['submit']))
{
$current_user = wp_get_current_user();
if ( $current_user->ID == 0 )
{
}
else
{
if( isset( $_POST['drop_artists'] ) )
{
$answer = $_POST['drop_artists'];
}
else
{
$answer = $_POST['artist_name'];
}
$date = current_time( 'mysql' );
$table = "t4t5_answers";
$sql = $wpdb->prepare( "INSERT INTO $table (user_id, post_id, info, answer, submission_date ) VALUES ( %d, %d, %s, %s, %d )", $current_user->ID, $post->ID, 'artist', $answer, $date );
$wpdb->query($sql);
}
echo "<script type='text/javascript'>
window.location=document.location.href;
</script>";
}
?>
<form method="post" action="" id="artists-form">
<ul>
<li id="categories">
<?php
$args = array(
'show_option_all' => 'Artists',
'hierarchical' => 1,
'child_of' => 406,
'order_by' => 'name',
'name' => 'answer',
'hide_empty' => 0
);
wp_dropdown_categories($args); ?>
</li>
</ul>
<input type="text" name="artist_name" value="" size="45" id="input-title"/>
<input id="submitButton" class="subput" type="submit" name="submit" value="Add"/>
</form>
This will refresh your page after form submit and form values will not be resubmitted.

Publish a custom post type from front

I want to publish a custom post type 'question' from the front-end, but when I submit the form I keep getting 404 error. Bellow is the form and form processing. What am I doing wrong?
<?
/**
* Questions processing
*/
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please add a question';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please add a description';
}
// Add the content of the form to $post as an array
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => 'question'
);
wp_insert_post($post); // Pass the value of $post to WordPress the insert function
} // end IF
// Do the wp_insert_post action to insert it
do_action('wp_insert_post', 'wp_insert_post');
?>
<h1>Add a question:</h1>
<!-- New Question Form -->
<div>
<form name="new_post" method="post" action="">
<p><label for="title">Question:</label><br />
<input type="text" value="" name="title" />
</p>
<p><label for="description">Details</label><br />
<textarea name="description" cols="50" rows="6"></textarea>
</p>
<p><input type="submit" value="Ask!" name="submit" /></p>
<input type="hidden" name="post_type" value="question" />
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
</div>
<!--// New Question Form -->
You don't actually need the add_action bit and I have a feeling is the $post variable itself that's causing issues.
/**
* Questions processing
*/
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please add a question';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please add a description';
}
// Add the content of the form to $post as an array
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => 'question'
);
$id = wp_insert_post($new_post); // Pass the value of $post to WordPress the insert function
//Returns ID of the new post you just created
And just in case, also add a URL to your form tag:
<form name="new_post" method="post" action="<?php the_permalink(); ?>">
I figured out:
I've deleted the line:
<input type="hidden" name="post_type" value="question" />
I think Wordpress is using somehow a post variable with this name and it get's an error if I use it on my own.

Categories