Create a New User via Form in Wordpress - wordpress

I am trying to create a page-template on wordpress that allows me to create a new user through a form on the front end of the website. Basically I want it to be laid out like how it currently is on the wordpress admin page but I need to make it work on the frontend.
(Layout would look like this)wordpress admin create new user page
The part that I'm stuck now is, when the user presses submit how can I handle the data and add it into the wordpress db? (Using this https://codex.wordpress.org/Function_Reference/wp_create_user)
(Code so far...) -
<?php
/**
* Template Name: Create User
*/
get_header('user');
?>
<?php // Start the Loop.
while ( have_posts() ) : the_post(); ?>
<div id="left-content">
<?php //GET THEME HEADER CONTENT
theme_title(get_the_title()); ?>
<!-- START CONTENT -->
<div id="content">
<?php if (woffice_is_user_allowed()) { ?>
<!-- PHP Create User -->
<?php
function add_user_from_form() {
$user_login = $_POST['email'];
$first_name = $_POST['fName'];
$last_name = $_POST['lName'];
$user_email = $_POST['email'];
$user_pass = $_POST['pass'];
$display_name = "{$first_name} {$last_name}";
$role = $_POST['role'];
$info = array(
'user_login' => $user_login,
'user_pass' => $user_pass,
'user_email' => $user_email,
'display_name' => $display_name,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => $role
);
$result = wp_insert_user( $info )
if ( is_wp_error( $result ) ) {
echo $result->get_error_message();
} else {
echo "Added user {$result}";
}
}
?>
<div class="box">
<form id="create-user-form" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>">
<div class="row">
<div class="col-md-12">
<input value="" name="fName" id="fName" placeholder="First Name" required="" type="text">
<input value="" name="lName" id="lName" placeholder="Last Name" required="" type="text">
<input value="" name="email" id="email" placeholder="Email" required="" type="text">
<input value="" name="pass" id="password" placeholder="Password" required="" type="Password">
<select name="role">
<option value="author">Author</option>
<option value="contributor">Contributor</option>
</select>
<input name="submit" type="submit" class="btn-ser" value="Create New User" style="width:160px !important; padding-left:18px;">
</div>
</div>
</form>
</div>
<?php } else {
get_template_part( 'content', 'private' );
}
?>
</div>
</div><!-- END #content-container -->
<?php theme_scroll_top(); ?>
</div><!-- END #left-content -->
<?php // END THE LOOP
endwhile; ?>

If you want to insert the data in the WP db, you can use the WP database API.
You can include the global wpdb object in your code to post the form data in your database.
global $wpdb;
Then use the insert function to post the data in db.
<?php $wpdb->insert( $table, $data, $format ); ?>
Check this link for more details : https://codex.wordpress.org/Class_Reference/wpdb#INSERT_rowenter link description here
Create a function in your functions.php like below to handle your post data:
function my_theme_send_email() {
if ( isset( $_POST['email-submission'] ) && '1' == $_POST['email-submission'] ) {
// Send the email...
} // end if
} // end my_theme_send_email
add_action( 'init', 'my_theme_send_email' );
Refer this link as well they have explained very nicely : https://tommcfarlin.com/sending-data-post/

Users need a login name for database. Login can be anything. Users do not need to know it, because users can login with email address.
I would use wp_insert_user().
Example:
function add_user_from_form() {
$now = time(); // unique number
$c = chr( ($now % 26) + 65 ); // random letter
$user_login = $c . strval( $now ); // unique user name
$first_name = $_POST['fName'];
$last_name = $_POST['lName'];
$user_email = $_POST['email'];
$user_pass = $_POST['pass'];
$display_name = "{$first_name} {$last_name}";
/*
VALIDATE USER DATA BEFORE ADDING TO DATABASE
*/
$info = array('user_login' => $user_login,
'user_pass' => $user_pass,
'user_email' => $user_email,
'display_name' => $display_name,
'first_name' => $first_name,
'last_name' => $last_name);
$result = wp_insert_user( $info )
if ( is_wp_error( $result ) ) {
echo $result->get_error_message();
} else {
echo "Added user {$result}";
}
}
Simplest way use this on a page is to create a template with a different header and process form on the same page.
E.g. Copy page.php to create-user.php and add the template header.
Copy header.php to header-user.php. Replace get_header() with
get_header('user').
Edit action on form:
<form id="my-registration-form" method="post" action="<?php echo $_SERVER['PHP_SELF']">
Add my function to the top of header with:
if ( 'POST` == $_SERVER['REQUEST_METHOD'] ) {
add_user_from_form();
}
You do not need an action. You just need to process form.
This does not conform to best practice of using MVC pattern, but it is easy and it will work.
Hope this clarifies earlier answer.

Related

How to make Guest post on Wordpress Frontend

Here is the code that I find to create a Form on the frontend page in WordPress to allow guests (visitors) to publish posts on the Blog section without logging in.
it has actually 3 steps and I applied it on WordPress Theme twenty twenty-two default theme.
but unfortunately, the Form shortcode does not apply to my mentioned section and it applies after my Body
tag (no matter where I callback the shortcode in Gutenberg).
So I have no idea about the Solution :(
Note: I don't want to do this by using any type of plugin... I know it sounds crazy but no plugin, please...
Step 1:
add bellow code to end line of my functions.php in 2022 WordPress Theme
//Add Shortcode-Form
require get_template_directory() . '/shortcode-form.php';
Step 2: Create shortcode-form.php file in theme's main folder
Step 3: add bellow lines to it:
add_shortcode( 'themedomain_frontend_post', 'themedomain_frontend_post' );
function themedomain_frontend_post() {
themedomain_post_if_submitted(); ?>
<form id="new_post" name="new_post" method="post" enctype="multipart/form-data">
<p><label for="title"><?php echo esc_html__( 'Title', 'theme-domain' ); ?></label><br />
<input type="text" id="title" value="" tabindex="1" size="20" name="title" />
</p>
<?php wp_editor( '', 'content' ); ?>
<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=category' ); ?></p>
<p><label for="post_tags"><?php echo esc_html__( 'Tags', 'theme-domain' ); ?></label>
<input type="text" value="" tabindex="5" size="16" name="post_tags" id="post_tags" />
</p>
<input type="file" name="post_image" id="post_image" aria-required="true">
<p><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p>
</form>
<?php
}
and:
function themedomain_post_if_submitted() {
// Stop running function if the form wasn't submitted
if ( ! isset( $_POST['title'] ) ) {
return;
}
// Add the content of the form to $post as an array
$post = array(
'post_title' => $_POST['title'],
'post_content' => $_POST['content'],
'post_category' => array( $_POST['cat'] ),
'tags_input' => $_POST['post_tags'],
'post_status' => 'draft', // Could be: publish
'post_type' => 'post', // Could be: 'page' or your CPT
);
$post_id = wp_insert_post( $post );
// For Featured Image
if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
require_once ABSPATH . 'wp-admin' . '/includes/image.php';
require_once ABSPATH . 'wp-admin' . '/includes/file.php';
require_once ABSPATH . 'wp-admin' . '/includes/media.php';
}
if ( $_FILES ) {
foreach ( $_FILES as $file => $array ) {
if ( $_FILES[ $file ]['error'] !== UPLOAD_ERR_OK ) {
return 'upload error : ' . $_FILES[ $file ]['error'];
}
$attach_id = media_handle_upload( $file, $post_id );
}
}
if ( $attach_id > 0 ) {
update_post_meta( $post_id, '_thumbnail_id', $attach_id );
}
echo 'Saved your post successfully! :)';
}
Here is the shortcode that I use in my gotenburg theme editor:
[themedomain_frontend_post]
Actually WordPress shortcode should run its own callback function, so it except a return variable. In this case you have echo inside callback function, that's why all the output comes at top of the page
Please try the code like bellow
add_shortcode( 'themedomain_frontend_post', 'themedomain_frontend_post' );
function themedomain_frontend_post() {
ob_start();
themedomain_post_if_submitted();
$return = "<form id='new_post' name='new_post' method='post' enctype='multipart/form-data'>
<p><label for='title'>" . esc_html__('Title','theme-domain') . "</label><br />
<input type='text' id='title' value='' tabindex='1' size='20' name='title' />
</p>". wp_editor( '', 'content' ) ."
<p>" . wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=category' ) ."</p>
<p><label for='post_tags'>" . esc_html__('Tags','theme-domain') . "</label>
<input type='text' value='' tabindex='5' size='16' name='post_tags' id='post_tags' /></p>
<input type='file' name='post_image' id='post_image' aria-required='true'>
<p><input type='submit' value='Publish' tabindex='6' id='submit' name='submit' /></p>
</form>";
$return .= ob_get_clean();
return $return;
}
it will solve the issue.

Use existing tags on Wordpress front-end posting

I have a front end posting to allow users to update their posts. Currently I'm using this to allow entering new tags:
This is my HTML form:
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
<input type="file" name="new_image_upload" id="new_image_upload" multiple="false" />
<input type="text" name="newtags" id="newtags" value="" />
<input type="hidden" name="post_id" id="post_id" value="" />
<?php wp_nonce_field( 'new_image_upload', 'new_image_upload_nonce' ); ?>
<input id="submit_new_image_upload" name="submit_new_image_upload" type="submit" value="Upload" />
</form>
This is part of the code:
// If the form has been submitted with new tags
if ( isset( $_POST['newtags'] ) ) {
// get existing tags
$post_tags = get_the_tags();
// concatenates both existing and new tags
$concatenated_tags = array($post_tags, sanitize_text_field($_POST['newtags']));
// Add all the tags to the post
wp_set_post_tags(get_the_ID(), $concatenated_tags , true );
}
The problem with this is that is creating many unecessary tags on my database and I need my users to see the sugestion of tags already present in my database.
So, I need that <input type="text" name="newtags" id="newtags" value="" /> make them existing tags sugestions, just like wordpress does on the post editing backend. See the image bellow to check the desired result on my front-end form:
I would recommend using Select2 javascript library for the frontend, specifically the automatic tokenization tagging functionality. See here: https://select2.org/tagging#automatic-tokenization-into-tags
Once you have enqued the Select2 file into your frontend you could do something like...
Your frontend form:
Note that I have added the $has_tag variable which will automatically select all saved tags for the current post. See selected()
<?php $post_id = get_the_ID(); ?>
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
...
<input type="hidden" name="post_id" value="<?= $post_id; ?>">
<select name="tags" multiple id="frontend-tagger">
<?php if ( $tags = get_terms( [ 'taxonomy' => 'post_tag', 'hide_empty' => false ] ) ): ?>
<?php foreach ( $tags as $tag ): ?>
<?php $has_tag = selected( has_tag( $tag->term_id, $post_id ), true, false ); ?>
<option value="<?= $tag->name; ?>"<?= $has_tag; ?>><?= $tag->name; ?></option>
<?php endforeach ?>
<?php endif ?>
</select>
...
</form>
JS to initiate the select2 field:
$( '#frontend-tagger' ).select2( {
tags: true,
tokenSeparators: [ ',' ]
} );
Saving process: Note because we are now including already saved tags in the pay load, we do not need to concat existing tags. We can now change the third paramater for wp_set_post_tags to false as we do not need to append tags.
$post_id = !empty( $_POST[ 'post_id' ] ) : (int)$_POST[ 'post_id' ] : null;
if ( isset( $_POST[ 'tags' ] ) ) {
// Sanitize array values
$tags = array_map( 'sanitize_text_field', $_POST[ 'tags' ] );
wp_set_post_tags( $post_id, $tags , false );
}
The above code hasn't been test, just a starting point for you to work from.
Hope this helps!

WordPress - How to prevent form resubmission?

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');

WordPress Creating Front end posting plugin

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.

How to create a woocommerce product from frontend form submission with form validation

Help Needed: I'm trying to create a form that will publish a wooCommerce product from front-end after following this question (Add Woocommerce Temporary product). The issue i'm facing now is that each time i submit the form i get this error (if i don't validate the form) Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\WOOstores\wp-includes\class.wp-styles.php:225) in C:\xampp\htdocs\WOOstores\wp-includes\pluggable.php on line 1219. I really would like to validate the form before submission and all i have been trying throws error related to WP_Error() below is the error i get when i try validating the form fields;
Warning: A non-numeric value encountered in C:\xampp\htdocs\WOOstores\wp-content\themes\adrianstores\woocommerce\myaccount\custom-orders.php on line 73 // Will indicate this line in my below code
Notice: Object of class WP_Error could not be converted to int in C:\xampp\htdocs\WOOstores\wp-includes\taxonomy.php on line 2297
Notice: Object of class WP_Error could not be converted to int in C:\xampp\htdocs\WOOstores\wp-includes\taxonomy.php on line 2297
Notice: Object of class WP_Error could not be converted to int in C:\xampp\htdocs\WOOstores\wp-includes\functions.php on line 3843
The product is being created with no problem, exactly how it should work ( if i don't validate the field), But i really want to validate the form but i'm having problems doing that. Below is the full code
<form method="post" action="">
<div class="form-group">
<div class="co-message"></div> <!--I want the validation message to show up here. Error & Success Validation-->
<label for="co_currency"><?php _e('Select Currency', 'text-domain'); ?></label>
<select class="form-control" id="co_currency" name="co_currency">
<option value="USD">USD</option>
<option value="RMB">RMB</option>
</select>
</div>
<div id="is_amazon" class="form-group is_amazon">
<label class="disInBlk" for="co_isAmazon"><?php _e('Is this an Amazon Product?','text-domain').':'; ?></label>
<input type="checkbox" name="co_isAmazon" id="co-isAmazon">
</div>
<div class="form-group">
<label for="co_productTitle"><?php _e('Product Name/Title','text-domain').':'; ?></label>
<input type="text" name="co_productTitle" class="form-control" id="co-productTitle" value="">
</div>
<div class="form-group">
<label for="co_productLink"><?php _e('Product Link','text-domain').':'; ?></label>
<input type="url" name="co_productLink" class="form-control" id="co-productLink" value="" placeholder="<?php _e('http://...', 'text-domain'); ?>">
</div>
<div class="form-group">
<label for="co_productPriceUSD"><?php _e('Product Price (USD)','text-domain').':'; ?></label>
<input type="number" name="co_productPriceUSD" class="form-control" id="co-productPriceUSD" value="0" step="0.01">
</div>
<div class="form-group">
<label for="co_productPriceNGN"><?php _e('Price Converted to NGN','text-domain').':'; ?></label>
<input type="number" name="co_productPriceNGN" class="form-control" id="co-productPriceNGN" value="0" readonly>
</div>
<div class="form-group">
<label for="co_productWeightKG"><?php _e('Weight (in KG)','text-domain').':'; ?></label>
<input type="number" name="co_productWeightKG" class="form-control" id="co-productWeightKG" value="" step="0.01">
</div>
<div class="form-group-btn">
<input type="submit" name="co_submit" class="form-control" id="co-submit" value="<?php echo _e('Place Your Order', 'text-domain'); ?>">
<input type="hidden" name="amountNGNUpdated" value="<?php echo $ExhangeRateUSD; ?>" id="CurrencyEX">
<input type="hidden" name="productCategoryUpdate" value="<?php echo $product_CO_terms; ?>">
</div>
</form>
PHP CODE which lives on the same page as the HTML form
function get_product_category_by_id( $category_id ) {
$term = get_term_by( 'id', $category_id, 'product_cat', 'ARRAY_A' );
return $term['name'];
}
$product_CO_terms = get_product_category_by_id( 15 );
$ProductTitle = $ProductURL = $ProductPriceValue = $ProductWeight = $ExchangeRate = "";
$errorpTitle = $errorpUrl= $errorpPrice = $errorpWeight = "";
if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
$ExchangeRate = test_input($_POST['amountNGNUpdated']);
$ProductCategory = test_input($_POST['productCategoryUpdate']);
$ProductTitle = test_input($_POST['co_productTitle']);
$ProductURL = test_input($_POST['co_productLink']);
$ProductPriceValue = test_input($_POST['co_productPriceUSD']);
$ProductWeight = test_input($_POST['co_productWeightKG']);
/* THIS IS THE VALIDATION I DID, Which i dont know why it giving me the WP_Error() error
if ( empty($ProductTitle) ) {
$errorpTitle = __('Product Title is required. e.g. iPhone XS Max 16GB Silver', 'text-domain');
} else {
$ProductTitle = test_input($_POST['co_productTitle']);
}
if ( empty($ProductURL) ) {
$errorpUrl = __('Product URL is required. e.g. http://amazon.com/.../', 'text-domain');
} else {
$ProductURL = test_input($_POST['co_productLink']);
}
if ( empty($ProductPriceValue) || $ProductPriceValue == 0 ) {
$errorpPrice = __('Product Price is required.', 'text-domain');
} else {
$ProductPriceValue = test_input($_POST['co_productPriceUSD']);
}
if ( empty($ProductWeight) ) {
$errorpWeight = __('Product Weight is required. Weight unit should be in KG. You can use the Weight converter to convert your weight from lbs to kg.', 'text-domain');
} else {
$ProductWeight = test_input($_POST['co_productWeightKG']);
}*/
$NewProductPrice = $ProductPriceValue * $ExchangeRate; //This is the line 73 in which i was getting "A non-numeric value encountered"
//add them in an array
$post = array(
'post_status' => "publish",
'post_title' => $ProductTitle,
'post_type' => "product",
);
//create product for product ID
$product_id = wp_insert_post( $post, __('Cannot create product', 'izzycart-function-code') );
//type of product
wp_set_object_terms($product_id, 'simple', 'product_type');
//Which Category
wp_set_object_terms( $product_id, $product_CO_terms, 'product_cat' );
//add product meta
update_post_meta( $product_id, '_regular_price', $NewProductPrice );
update_post_meta( $product_id, '_price', $NewProductPrice );
update_post_meta( $product_id, '_weight', $ProductWeight );
update_post_meta( $product_id, '_store_product_uri', $ProductURL );
update_post_meta( $product_id, '_visibility', 'visible' );
update_post_meta( $product_id, '_stock_status', 'instock' );
//Add product to Cart
return WC()->cart->add_to_cart( $product_id );
What i would like to achieve with the above line return WC()->cart->add_to_cart( $product_id ); is to the add product to cart and redirect to cart. (using return give me a blank page but adds the product to get which makes the line not the best approach)
HELP I NEED;
1. How to make the form validate the field. If any field is empty, it should throw an error message at the top of the form. Where we have <div class="co-message"></div> and if all field passes the validation, it should throw a success message and proceed to creating the product.
2. After creating the product, it should add the product to cart and redirect to cart.
Thanks
I have been able to validate the form and create product has i wanted it to work. Just incase someone out there is facing similar issue and would want the answer to this question.
PHP CODE:
$ProductTitle = $ProductURL = $ProductPriceValue = $ProductShippingFee = $ProductWeight = "";
$error_pTitle = $error_pLink = $error_pPrice = $error_pShipping = $error_pweight = $success_call = "";
$productPrice_converted = "";
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_REQUEST['co_submit']) ) {
$ExchangeRate = test_input($_POST['amountNGNUpdated']);
$ProductCategory = test_input($_POST['productCategoryUpdate']);
//Validate Product Title
if( empty( test_input($_POST['co_productTitle']) ) ) {
$error_pTitle = __('Product Title is required.', 'izzycart-function-code');
} else {
$ProductTitle = test_input($_POST['co_productTitle']);
}
//Validate Product URL
if( empty( test_input($_POST['co_productLink']) ) ) {
$error_pLink = __('Product Link is required.', 'izzycart-function-code');
} elseif ( !preg_match("#^https?://#", test_input($_POST['co_productLink']) ) ) {
$error_pLink = __('Please enter a url that starts with http:// or https://', 'izzycart-function-code');
} elseif ( isset($_POST['co_isAmazon']) == 1 && strpos($_POST['co_productLink'], 'amazon') === false ) {
$error_pLink = __('This is not an Amazon product. Please enter a valid amazon product.', 'izzycart-function-code');
} else {
$ProductURL = test_input($_POST['co_productLink']);
}
//Validate Product Price
if( empty( test_input($_POST['co_productPriceUSD']) ) || test_input($_POST['co_productPriceUSD']) == 0 ) {
$error_pPrice = __('Product Price is required.', 'izzycart-function-code');
} else {
$ProductPriceValue = test_input($_POST['co_productPriceUSD']);
}
//Validate Product Shipping
if( empty( test_input($_POST['co_productShippingFee']) ) ) {
$error_pShipping = __('Product Shipping fee is required.', 'izzycart-function-code');
} else {
$ProductShippingFee = test_input($_POST['co_productShippingFee']);
}
//Validate Product Weight
if( empty( test_input($_POST['co_productWeightKG']) ) || test_input($_POST['co_productWeightKG']) == 0 ) {
$error_pweight = __('Product Weight is required. Weight are in KG, use the weight converter to covert your lbs item to KG', 'izzycart-function-code');
} else {
$ProductWeight = round(test_input($_POST['co_productWeightKG']), 2);
}
if ($ProductPriceValue && $ExchangeRate ) {
$productPrice_converted = $ProductPriceValue * $ExchangeRate;
}
//No Errors Found
if ( $error_pTitle == "" && $error_pLink == "" && $error_pPrice == "" && $error_pShipping = "" $error_pweight == "" ) {
//add them in an array
$post = array(
'post_status' => "publish",
'post_title' => $ProductTitle,
'post_type' => "product",
);
//create product for product ID
$product_id = wp_insert_post( $post, __('Cannot create product', 'izzycart-function-code') );
//type of product
wp_set_object_terms($product_id, 'simple', 'product_type');
//Which Category
wp_set_object_terms( $product_id, $product_CO_terms, 'product_cat' );
//add product meta
update_post_meta( $product_id, '_regular_price', $productPrice_converted );
update_post_meta( $product_id, '_price', $productPrice_converted );
update_post_meta( $product_id, '_weight', $ProductWeight );
update_post_meta( $product_id, '_store_product_uri', $ProductURL );
update_post_meta( $product_id, '_visibility', 'visible' );
update_post_meta( $product_id, '_stock_status', 'instock' );
//Add Product To cart
$found = false;
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
//Sending Mail to Admin
//I installed an application hMailServer on my PC, because i was working on a local
//server (XAMPP) and it wont send out mail(), so i wasn't getting the success message
//as soon as i installed the application.. the mail() function worked and i get the success message
//and product is added to cart. Though didn't receive the mail in my inbox for reason i don't know but i
//will update this answer to confirm that the sending mail works. but the fact that i got the success message. it will work on a LIVE server
$message_bd = '';
unset($_POST['co_submit']);
foreach ($_POST as $key => $value) {
$message_bd .= "$key: $value\n";
}
$to = $AdminEmailFor_CO; //This is a custom field i created which stores the admin email in the database and can be changed from wordpress dashboard (you can write directly your admin email)
$subject = $SubjectFor_CO; // Same as the subject. They are stored the in options table
$header = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if ( mail($to, $subject, $message_bd ) ) {
//Success Message & reset Fields
$success_call = sprintf(__('Success: Product has been added to your cart. Click the view cart button below to proceed with your custom order. View Cart', 'izzycart-function-code'), wc_get_cart_url() );
$ProductTitle = $ProductURL = $ProductPriceValue = $ProductWeight = "";
$productPrice_converted = 0;
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
HTML FORM has been updated to the below
<form method="post" action="">
<div class="co-success"><?= $success_call ?></div>
<div class="form-group">
<label for="co_currency"><?php _e('Select Currency', 'izzycart-function-code'); ?></label>
<select class="form-control" id="co_currency" name="co_currency">
<option value="USD">USD</option>
<option value="RMB">RMB</option>
</select>
</div>
<div id="is_amazon" class="form-group is_amazon">
<label class="disInBlk" for="co_isAmazon"><?php _e('Is this an Amazon Product?','izzycart-function-code').':'; ?></label>
<input type="checkbox" name="co_isAmazon" id="co-isAmazon" <?php echo (isset($_POST['co_isAmazon'])?'checked="checked"':'') ?>>
</div>
<div class="form-group">
<label for="co_productTitle"><?php _e('Product Name/Title','izzycart-function-code').':'; ?></label>
<input type="text" name="co_productTitle" class="form-control" id="co-productTitle" value="<?= $ProductTitle ?>">
<div class="co-error"><?php echo $error_pTitle ?></div>
</div>
<div class="form-group">
<label for="co_productLink"><?php _e('Product Link','izzycart-function-code').':'; ?></label>
<input type="text" name="co_productLink" class="form-control" id="co-productLink" value="<?= $ProductURL ?>" placeholder="<?php _e('http://...', 'izzycart-function-code'); ?>">
<div class="co-error"><?php echo $error_pLink ?></div>
</div>
<div class="form-group">
<label for="co_productPriceUSD"><?php _e('Product Price (USD)','izzycart-function-code').':'; ?></label>
<input type="number" name="co_productPriceUSD" class="form-control" id="co-productPriceUSD" value="<?= $ProductPriceValue ?>" step="0.01">
<div class="co-error"><?php echo $error_pPrice ?></div>
</div>
<div class="form-group">
<label for="co_productShippingFee"><?php _e('Shipping Fee of Product/Item','izzycart-function-code').':'; ?></label>
<div class="co-desc"><?php echo __('N.B: If the product is FREE shipping from the store you\'re buying from, enter 0 as the shipping fee.', 'izzycart-function-code'); ?></div>
<input type="number" name="co_productShippingFee" class="form-control" id="co_productShippingFee" value="<?= $ProductShippingFee ?>" step="0.01">
<div class="co-error"><?php echo $error_pShipping ?></div>
</div>
<div class="form-group">
<label for="co_productPriceNGN"><?php _e('Product Price Converted to NGN','izzycart-function-code').':'; ?></label>
<input type="number" name="co_productPriceNGN" class="form-control" id="co-productPriceNGN" value="<?= $productPrice_converted ?>" readonly>
</div>
<div class="form-group">
<label for="co_productWeightKG"><?php _e('Weight (in KG)','izzycart-function-code').':'; ?></label>
<input type="number" name="co_productWeightKG" class="form-control" id="co-productWeightKG" value="<?= $ProductWeight ?>" step="0.001">
<div class="co-error"><?php echo $error_pweight ?></div>
</div>
<div class="form-group-btn">
<input type="submit" name="co_submit" class="form-control" id="co-submit" value="<?php echo _e('Place Your Order', 'izzycart-function-code'); ?>">
<input type="hidden" name="amountNGNUpdated" value="<?php echo $ExhangeRateUSD; ?>" id="CurrencyEX">
<input type="hidden" name="productCategoryUpdate" value="<?php echo $product_CO_terms; ?>">
</div>
</form>
The result looks like this
showing the validation

Resources