WordPress Creating Front end posting plugin - wordpress

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.

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.

Add a link for a button

Hello i need to add a link in the following code to redirect the (submit button)
Here the code
<form class="checkout adq-billing" enctype="multipart/form-data" action="<?php echo StaticAdqQuoteRequest::get_quote_list_link() ?>" method="post" name="checkout">
<div class="col2-set">
<?php
//Billing/Account information
//, 'is_billing_filled' => $is_billing_filled
adq_get_template( 'adq-form-billing-details.php', array( 'checkout' => StaticAdqQuoteRequest::get_checkout() ) );
?>
<div class="col-2">
<?php
//Force enabled to avoid core Woocommerce system
$shipping->enabled = StaticAdqQuoteRequest::is_shipping_enabled();
//Get Shipping options and address
$shipping->calculate_shipping( WC_Adq()->quote->get_shipping_packages() );
$packages = $shipping->get_packages();
if ( $shipping->enabled ) :
if ( get_option( 'adq_enable_shipping' ) == "user" ) : ?>
<label for="include-shipping-cost">
<?php _e( 'Would you want to include the shipping cost in quotation?', 'woocommerce-quotation' ); ?> <input id="include-shipping-cost" type="checkbox" name="include-shipping-cost" value="1" checked />
</label>
<?php endif;
if ( get_option( 'woocommerce_ship_to_destination' ) != "billing_only" ) :
adq_get_template( 'adq-form-shipping.php', array( 'checkout' => WC()->checkout() ) );
endif;
echo '<div class="adq-shipping">';
foreach ( $packages as $i => $package ) {
$chosen_method = isset( WC()->session->chosen_shipping_methods[ $i ] ) ? WC()->session->chosen_shipping_methods[ $i ] : '';
adq_get_template( 'adq-cart-shipping.php', array( 'package' => $package, 'available_methods' => $package['rates'], 'show_package_details' => ( sizeof( $packages ) > 1 ), 'index' => $i, 'chosen_method' => $chosen_method ) );
};
echo '</div>';
endif;
?>
<p id="quote_comments_field" class="form-row notes woocommerce-validated">
<label class="" for="order_comments"><?php echo __('Message','woocommerce-quotation') ?></label>
<textarea cols="5" rows="2" placeholder="<?php echo __('Please Any other requirements.','woocommerce-quotation') ?>" id="order_comments" class="input-text" name="order_comments" required></textarea>
</p>
</div>
</div>
<?php if ( wc_get_page_id( 'terms' ) > 0 && apply_filters( 'adq_checkout_show_terms', true ) ) : ?>
<p class="form-row terms">
<label for="terms" class="checkbox"><?php printf( __( 'I’ve read and accept the terms & conditions', 'woocommerce-quotation' ), esc_url( get_permalink( wc_get_page_id( 'terms' ) ) ) ); ?></label>
<input type="checkbox" class="input-checkbox" name="terms" <?php checked( apply_filters( 'woocommerce_terms_is_checked_default', isset( $_POST['terms'] ) ), true ); ?> id="terms" />
</p>
<?php endif; ?>
<input type="submit" data-value="<?php echo __('Submit Quote Request','woocommerce-quotation') ?>" value="<?php echo __('Submit','woocommerce-quotation') ?>" id="quote_place_order" name="adq_quote_place_order" class="button alt">
<a class="button wc-backward return-to-shop" href="http://localhost/test"><?php _e( 'Go Back', 'woocommerce-quotation' ) ?></a>
<input type="hidden" name="_wpnonce" value="<?php echo wp_create_nonce('woocommerce-process_checkout'); ?>">
</form>
#############################################################
I have added a link and it works but the form was not submitted, is there's any way to submit a form with url redirection, view code
The tag <input type="submit" /> is used to submit a form.
You will find that this INPUT is inside a <form action=""> tag. action="" is the path the form will be submit to.
If you don't need to submit the form, simply use a tag <a></a>.
<a href="#your-link.php" id="quote_place_order" name="adq_quote_place_order" class="button alt">
<?php echo __('Submit','woocommerce-quotation') ?>
</a>
You need a Form tag so you could add an action attribute to that. Now by clicking the submit button your form will be redirected to the URL that u assigned to the form.
<form action="site.com">
<input type="submit">
</form>

Create a New User via Form in 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.

Wordpress - Category list order in post edit page

I want to stop WordPress re-ordering the category list in the admin > post edit page. The default behaviour is to take the categories assigned to the post out of their natural parent/child flow and put them at the top of the list. I want to stop this happening as it is confusing when the category structure is big.
Any thoughts?
Thanks.
While the above are great alternative solutions, especially if you want more control over the taxonomy checklist metabox, I think the simplest solution would be the following:
function taxonomy_checklist_checked_ontop_filter ($args)
{
$args['checked_ontop'] = false;
return $args;
}
add_filter('wp_terms_checklist_args','taxonomy_checklist_checked_ontop_filter');
And that should take care of that!
What version of Wordpress are you using? Wordpress 3.04 provides the Parent/Child tree on the Post Edit page. Are you sure you also aren't viewing the "Most Used" tab?
Nevermind, I see exactly the problem you are talking about, which show up after the post is saved:
Alright, try pasting this into the functions.php in your theme:
// remove the old box
function remove_default_categories_box() {
remove_meta_box('categorydiv', 'post', 'side');
}
add_action( 'admin_head', 'remove_default_categories_box' );
// add the new box
function add_custom_categories_box() {
add_meta_box('customcategorydiv', 'Categories', 'custom_post_categories_meta_box', 'post', 'side', 'low', array( 'taxonomy' => 'category' ));
}
add_action('admin_menu', 'add_custom_categories_box');
/**
* Display CUSTOM post categories form fields.
*
* #since 2.6.0
*
* #param object $post
*/
function custom_post_categories_meta_box( $post, $box ) {
$defaults = array('taxonomy' => 'category');
if ( !isset($box['args']) || !is_array($box['args']) )
$args = array();
else
$args = $box['args'];
extract( wp_parse_args($args, $defaults), EXTR_SKIP );
$tax = get_taxonomy($taxonomy);
?>
<div id="taxonomy-<?php echo $taxonomy; ?>" class="categorydiv">
<ul id="<?php echo $taxonomy; ?>-tabs" class="category-tabs">
<li class="tabs"><?php echo $tax->labels->all_items; ?></li>
<li class="hide-if-no-js"><?php _e( 'Most Used' ); ?></li>
</ul>
<div id="<?php echo $taxonomy; ?>-pop" class="tabs-panel" style="display: none;">
<ul id="<?php echo $taxonomy; ?>checklist-pop" class="categorychecklist form-no-clear" >
<?php $popular_ids = wp_popular_terms_checklist($taxonomy); ?>
</ul>
</div>
<div id="<?php echo $taxonomy; ?>-all" class="tabs-panel">
<?php
$name = ( $taxonomy == 'category' ) ? 'post_category' : 'tax_input[' . $taxonomy . ']';
echo "<input type='hidden' name='{$name}[]' value='0' />"; // Allows for an empty term set to be sent. 0 is an invalid Term ID and will be ignored by empty() checks.
?>
<ul id="<?php echo $taxonomy; ?>checklist" class="list:<?php echo $taxonomy?> categorychecklist form-no-clear">
<?php
/**
* This is the one line we had to change in the original function
* Notice that "checked_ontop" is now set to FALSE
*/
wp_terms_checklist($post->ID, array( 'taxonomy' => $taxonomy, 'popular_cats' => $popular_ids, 'checked_ontop' => FALSE ) ) ?>
</ul>
</div>
<?php if ( !current_user_can($tax->cap->assign_terms) ) : ?>
<p><em><?php _e('You cannot modify this taxonomy.'); ?></em></p>
<?php endif; ?>
<?php if ( current_user_can($tax->cap->edit_terms) ) : ?>
<div id="<?php echo $taxonomy; ?>-adder" class="wp-hidden-children">
<h4>
<a id="<?php echo $taxonomy; ?>-add-toggle" href="#<?php echo $taxonomy; ?>-add" class="hide-if-no-js" tabindex="3">
<?php
/* translators: %s: add new taxonomy label */
printf( __( '+ %s' ), $tax->labels->add_new_item );
?>
</a>
</h4>
<p id="<?php echo $taxonomy; ?>-add" class="category-add wp-hidden-child">
<label class="screen-reader-text" for="new<?php echo $taxonomy; ?>"><?php echo $tax->labels->add_new_item; ?></label>
<input type="text" name="new<?php echo $taxonomy; ?>" id="new<?php echo $taxonomy; ?>" class="form-required form-input-tip" value="<?php echo esc_attr( $tax->labels->new_item_name ); ?>" tabindex="3" aria-required="true"/>
<label class="screen-reader-text" for="new<?php echo $taxonomy; ?>_parent">
<?php echo $tax->labels->parent_item_colon; ?>
</label>
<?php wp_dropdown_categories( array( 'taxonomy' => $taxonomy, 'hide_empty' => 0, 'name' => 'new'.$taxonomy.'_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => '— ' . $tax->labels->parent_item . ' —', 'tab_index' => 3 ) ); ?>
<input type="button" id="<?php echo $taxonomy; ?>-add-submit" class="add:<?php echo $taxonomy ?>checklist:<?php echo $taxonomy ?>-add button category-add-sumbit" value="<?php echo esc_attr( $tax->labels->add_new_item ); ?>" tabindex="3" />
<?php wp_nonce_field( 'add-'.$taxonomy, '_ajax_nonce-add-'.$taxonomy, false ); ?>
<span id="<?php echo $taxonomy; ?>-ajax-response"></span>
</p>
</div>
<?php endif; ?>
</div>
<?php
}
The only real change was adding 'checked_ontop' => FALSE to the args in wp_terms_checklist() function in the middle of that mess. Everything else is the original post_categories_meta_box() function.
(You could just modify the original post_categories_meta_box() in /wp-admin/includes/meta-boxes.php, but it is not recommended to mess with core and adding/removing actions as above is the proper way to do it.
There's a plugin that does just this http://wordpress.org/extend/plugins/category-checklist-tree/

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