I have a Woocommerce search form which works fine however I want it to find products not just by what is written in the short description but also by their category name.
For example we have 300 products in the vegetarian category but when you search for "vegetarian" only 6 products show up as only 6 have this keyword in the short description so is giving a poor user experience.
Is there a way to include the category title in the search box query?
// custom product search form
add_filter( 'get_product_search_form' , 'me_custom_product_searchform' );
function me_custom_product_searchform( $form ) {
$form = '<form role="search" method="get" id="searchform" action="' . esc_url( home_url( '/' ) ) . '">
<input type="text" value="' . get_search_query() . '" name="s" id="s" placeholder="' . __( 'Search for your favourite crisps', 'woocommerce' ) . '" />
<input type="hidden" name="post_type" value="product" />
<button type="submit" id="searchsubmit" />
<span class="icon"><img src="https://onepoundcrisps.com/wp-content/uploads/2022/02/search-icon.png" alt="search icon"></span>
</button>
</form>';
return $form
}
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 );
i am new with wordpress.
I have modify search form in wordpress.
<form class="form-inline" role="form" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
<div class="form-group">
<input type="search" class="form-control" placeholder="Type your search" value="" name="query" />
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
In this form i have modify name attribute of Search input box name='s' to name='query'.
But after that search is not working .
Do i need to write anything in function.php to Get query string.
Try this code, i hope this will help you to workout,
Add this in theme's fuctions.php file:-
add_filter( 'query_vars', 'my_query_vars' );
function my_query_vars( $query_vars )
{
if ( isset( $_GET['query'] ) && ! empty( $_GET['query'] ) ) {
$_GET['s'] = $_GET['query'];
}
return $query_vars;
}
I've got my own custom registration form, and it allows people to register except for one small issue: the checkboxes don't do anything. When I check the meta_key fields in the database, they don't exist. Everything else is OK though.
I'm trying to have 'comps' and 'newsletter' get added to the meta_key fields (with a value of 1) when they checkboxes are ticked. My form looks like this:
<form id="form" action="<?php echo site_url('wp-login.php?action=register', 'login_post') ?>" method="post">
<fieldset>
<label for="user-login">Username<br />
<input type="text" name="user_login" id="user-login" class="input" value="" size="20" tabindex="10" />
<label for="user-email">Email address<br />
<input type="text" name="user_email" id="user-email" class="input" value="" size="25" tabindex="20" />
<label for="comps">Competitions<br />
<input type="checkbox" name="comps" id="comps" class="" value="1" tabindex="30" /></label>
<label for="newsletter">Newsletter<br />
<input type="checkbox" name="newsletter" id="newsletter" class="" value="1" tabindex="40" /></label>
<input type="hidden" name="redirect_to" value="<?php echo get_settings('home'); ?>/registration-succeeded"/>
<input type="submit" name="wp-submit" class="button" value="Register Me!" tabindex="100" />
</fieldset>
Is there something I need to do in functions.php of my theme to get these meta_fields to go into the database when the user registers (and when the checkboxes are ticked of course)?
Thanks in advance.
I've worked it out. Just needed to register these extra fields for metadata use:
function at_register_custom_fields( $user_id, $password = "", $meta = array() ) {
// custom fields
$fields = array(
'comps',
'newsletter',
);
// cleans and updates the custom fields
foreach ( $fields as $field ) {
$value = stripslashes( trim( $_POST[$field] ) ) ;
if ( ! empty( $value ) ) {
update_user_meta( $user_id, $field, $value );
}
}
}
add_action( 'user_register', 'at_register_custom_fields' );
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