Display on particular category and manage by admin - wordpress

I want to make calculator should be display on particular category. I have added a code for flag if display flag is on then show if not then hide. Basically its hide show based on product belongs to which category. For example automobile then calculate fule if fruit then should not display.
/*
* Display input on single product page
* #return html
*/
function wallc_custom_option(){
global $post;
// when its display
if($display_flag){
// Logic of calling calculator
$wall_width_value = isset( $_POST['wall_width_value'] ) ? sanitize_text_field( $_POST['wall_width_value'] ) : '';
$wall_height_value = isset( $_POST['wall_height_value'] ) ? sanitize_text_field( $_POST['wall_height_value'] ) : '';
printf( '<div class="rollcalculator">');
?>
<div class="form-group"><label class="control-label" >Wall width</label>
<input class="form-control control-label" id="wall_width_value" name="wall_width_value" />
</div>
<div class="form-group">
<label class="control-label" >Wall height</label>
<input class="form-control control-label" id="wall_height_value" name="wall_height_value" />
</div>
<div class="form-group"> <p><button id="estimateRole" class="btn btn-info btn-block" onclick="myFunction()">Estimate number of rolls</button></p></div>
<?php
global $product;
$dimensions = $product->get_dimensions();
if ( ! empty( $dimensions ) ) {
// all in cm
$height= $product->get_height();
$width=$product->get_width();
$length=$product->get_length();
// CONVERT TO METER
$pattern_height= $height/100;
$pattern_width= $width/100;
$pattern_repeat= $length/100;
echo '<input type="hidden" id="pattern_height" value="'.$pattern_height.'" />';
echo '<input type="hidden" id="pattern_width" value="'.$pattern_width.'"/>';
echo '<input type="hidden" id="pattern_repeat" value="'.$pattern_repeat.'"/>';
echo '<div class="form-group"><label class="control-label" >Roll Required</label><label class="form-control" id="totalRole"></label></div>';
//correct
// $WALL_AREA = ceil(($wall_width_value+$pattern_height) * $wall_height_value);
?>
<script type="text/javascript">
function myFunction(){
}
</script>
<?php
}
}
}
add_action( 'woocommerce_after_single_product_summary', 'wallc_custom_option', 9 );

you have to get terms and fetch a details based on that change a display flag if find category then break loop and execute rest of code.
/*
* Display input on single product page
* #return html
*/
function wallc_custom_option(){
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat' );
$display_flag=false;
foreach ( $terms as $term )
{
$wh_meta_checkbox = get_term_meta($term->term_id, 'wh_meta_checkbox', true);
if($wh_meta_checkbox == 'on'){
$display_flag=true;
break;
}
}
// when its display
if($display_flag){
// Logic of calling calculator
$wall_width_value = isset( $_POST['wall_width_value'] ) ? sanitize_text_field( $_POST['wall_width_value'] ) : '';
$wall_height_value = isset( $_POST['wall_height_value'] ) ? sanitize_text_field( $_POST['wall_height_value'] ) : '';
printf( '<div class="rollcalculator">');
?>
<div class="form-group"><label class="control-label" >Wall width</label>
<input class="form-control control-label" id="wall_width_value" name="wall_width_value" />
</div>
<div class="form-group">
<label class="control-label" >Wall height</label>
<input class="form-control control-label" id="wall_height_value" name="wall_height_value" />
</div>
<div class="form-group"> <p><button id="estimateRole" class="btn btn-info btn-block" onclick="myFunction()">Estimate number of rolls</button></p></div>
<?php
global $product;
$dimensions = $product->get_dimensions();
if ( ! empty( $dimensions ) ) {
// all in cm
$height= $product->get_height();
$width=$product->get_width();
$length=$product->get_length();
// CONVERT TO METER
$pattern_height= $height/100;
$pattern_width= $width/100;
$pattern_repeat= $length/100;
echo '<input type="hidden" id="pattern_height" value="'.$pattern_height.'" />';
echo '<input type="hidden" id="pattern_width" value="'.$pattern_width.'"/>';
echo '<input type="hidden" id="pattern_repeat" value="'.$pattern_repeat.'"/>';
echo '<div class="form-group"><label class="control-label" >Roll Required</label><label class="form-control" id="totalRole"></label></div>';
//correct
// $WALL_AREA = ceil(($wall_width_value+$pattern_height) * $wall_height_value);
?>
<script type="text/javascript">
function myFunction(){
// wall input
wall_width_value=Number($("#wall_width_value").val());
wall_height_value=Number($("#wall_height_value").val());
// Product dimensions
pattern_height=Number($("#pattern_height").val());
pattern_width=Number($("#pattern_width").val());
pattern_repeat=Number($("#pattern_repeat").val());
WALL_AREA = Math.ceil((wall_width_value+pattern_height) * wall_height_value);
wall_width_value_meter=wall_width_value/100;
pattern_width_meter=pattern_width;
PATTERN_AREA = (pattern_width * pattern_repeat) ;
totalRole=Math.ceil(WALL_AREA/PATTERN_AREA);
$("#totalRole").text(totalRole);
}
</script>
<?php
}
}
}
add_action( 'woocommerce_after_single_product_summary', 'wallc_custom_option', 9 );

Related

Custom Wordpress Search Result Page Displays 404

Custom Wordpress Search Result Page not working and redirects to 404.
Target Url: https://example.com/blog/search/?post_type=post&s=a
// CUSTOM BLOG POST SEARCH FORM
function blog_search_form( $blog_form ) {
$blog_form = '
<form class="form-inline" id="search" action="'.home_url( "/blog/search/" ).'" method="get">
<div class="form-group mx-sm-1 mb-2 w-100">
<input type="hidden" name="post_type" value="post" />
<input class="form-control w-100" id="s" name="s" type="text" placeholder="Search blog" value="' . get_query_var('s') . '" required />
</div>
<input id="searchsubmit" class="main-btn btn mb-2" type="submit" value="Search" />
</form>';
return $blog_form;
}
add_filter( 'get_search_form', 'blog_search_form' );
// CHANGE URL FUNCTION
/function wpb_change_search_url() {
if ( is_search() && ! empty( $_GET['s'] ) ) {
wp_redirect( home_url( "/blog/search/" ) . urlencode( get_query_var( 's' ) ) );
exit();
}
}
add_action( 'template_redirect', 'wpb_change_search_url' );

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>

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.

Posting from the frontend mostly working

I'm using this front end code to create a post. At the moment it does create a post but the only thing that works is the title.
I also have a custom metabox with some fields (more_info, priority and duedate and ) in my post as well but I'm not sure if I'm putting them in the array correctly. Note that in the backend those additional fields work just fine.
Here's my code:
<?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
}
// Add the content of the form to $post as an array
$post = array(
'post_title' => $title,
'post_content' => $description,
'more_info' => $more_info,
'priority' => $priority,
'duedate' => $duedate,
'post_category' => $_POST['cat'],
'post_status' => 'publish',
'post_type' => $_POST['post']
);
wp_insert_post($post);
}
do_action('wp_insert_post', 'wp_insert_post');
?>
<form action="" id="new_post" method="post">
<label for="title">Task Name </label>
<input type="text" id="title" name="title" value="" />
<label for="minfo">Additional information</label>
<textarea name="minfo" id="minfo" value=""></textarea>
<label>Due date</label>
<input type="text" id="duedate" name="duedate" />
<strong>Priority</strong>
<label><input type="radio" name="priority" value="low" id="low">Low</label>
<label><input type="radio" name="priority" value="normal" id="normal" checked>Normal</label>
<label><input type="radio" name="priority" value="high" id="high">High</label>
<label><input type="radio" name="priority" value="urgent" id="urgent">Urgent</label>
<input type="submit" name="submit" value="Add" />
<input type="hidden" name="cat" id="cat" value="<?php echo $cat_id = get_query_var('cat'); ?>" />
<input type="hidden" name="post_type" id="post_type" value="post" />
<input type="hidden" name="action" value="post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
Any assistance would be awesome.
Okay, couple things:
It's not clear to me what you're trying to do here. Do you need users to have the ability to add the values submitted in this meta box to any post? If not, why not create a custom post type that you can tweak to your heart's content?
If the answer to #1 is yes, then you're still going to want to attach your save methods differently. Something like:
add_meta_box(
'my-custom-meta', // Unique ID
esc_html__('Custom Attributes', 'my_scope'), // Title
'my_custom_meta_box', // Callback function
'post', // Admin page (or post type)
'normal', // Context
'high' // Priority
);
function my_custom_meta_box( $object ) { ?>
<?php wp_nonce_field( 'my_custom_inner', 'my_custom_inner_nonce' ); ?>
<p>
<label for="minfo">Additional information</label>
<textarea name="minfo" id="minfo" value="<?php echo esc_attr( get_post_meta( $object->ID, 'minfo', true ) ); ?>"></textarea>
</p>
<p>
<label>Due date</label>
<input type="text" id="duedate" name="duedate" value="<?php echo esc_attr( get_post_meta( $object->ID, 'duedate', true ) ); ?>" />
</p>
<p>
<strong>Priority</strong>
<label><input type="radio" name="priority" value="low" id="low"<?php if ( get_post_meta( $object->ID, 'priority', true ) == 'low' ) { echo ' checked'; }?>>Low</label>
<label><input type="radio" name="priority" value="normal" id="normal"<?php if ( get_post_meta( $object->ID, 'priority', true ) == 'normal' ) { echo ' checked'; }?>>Normal</label>
<label><input type="radio" name="priority" value="high" id="high"<?php if ( get_post_meta( $object->ID, 'priority', true ) == 'high' ) { echo ' checked'; }?>>High</label>
<label><input type="radio" name="priority" value="urgent" id="urgent"<?php if ( get_post_meta( $object->ID, 'priority', true ) == 'urgent' ) { echo ' checked'; }?>>Urgent</label>
</p>
<?php }
function save_my_meta( $post_id ) {
// Check if our nonce is set.
if ( ! isset( $_POST['my_custom_inner_nonce'] ) )
return $post_id;
$nonce = $_POST['my_custom_inner_nonce'];
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce, 'my_custom_inner' ) )
return $post_id;
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions.
if ( $_REQUEST['post_type'] == 'post' ) {
if ( ! current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
/* Cast the returned vaiables to an array for processing */
$my_meta['minfo'] = $_REQUEST['minfo'];
$my_meta['duedate'] = $_REQUEST['duedate'];
$my_meta['priority'] = $_REQUEST['priority'];
foreach ( $my_meta as $key => $value ) { // Cycle through the $events_meta array!
if(get_post_meta( $post_id, $key ) ) { // If the custom field already has a value
update_post_meta( $post_id, $key, sanitize_text_field( $value ) );
} else {
add_post_meta( $post_id, $key, sanitize_text_field ( $value ) );
}
if( !$value ) delete_post_meta( $post_id, $key ); // Delete if blank
}
}
add_action( 'save_post', 'save_my_meta' );

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