Multiple checkbox search wordpress - wordpress

I need a multiple checkbox search to work and I'm stuck. The form is ok but I don't know how to do the query. an someone please help me ?
Form :
<input id="propertytype" class="noborder" type="checkbox" name="propertytype2[]" value="Loft"><div class="lbl">Loft</div>
<input id="propertytype" class="noborder" type="checkbox" name="propertytype2[]" value="Studio"><div class="lbl">Studio</div>
<input id="propertytype" class="noborder" type="checkbox" name="propertytype2[]" value="2 pieces"><div class="lbl">2 pièces</div>
<input id="propertytype" class="noborder" type="checkbox" name="propertytype2[]" value="3 pieces"><div class="lbl">3 pièces</div>
<input id="propertytype" class="noborder" type="checkbox" name="propertytype2[]" value="4 pieces"><div class="lbl">4 pièces</div>
<input id="propertytype" class="noborder" type="checkbox" name="propertytype2[]" value="5 pieces"><div class="lbl">5 pièces</div>
<input id="propertytype" class="noborder" type="checkbox" name="propertytype2[]" value="6 pieces et +"><div class="lbl">6 pièces et +</div>
<input id="propertytype" class="noborder" type="checkbox" name="propertytype2[]" value="Proprietes, Hotels particuliers"><div class="lbl">Propriétés, Hôtels particuliers</div>
Query :
$search_propertytype = "";
if (isset($_POST['propertytype2'])) {
$search_propertytype = trim($_POST['propertytype2']);
}
if (get_option('wp_search_propertytype') == "Yes") {
if($search_propertytype != '')
{
$search_propertytype = trim($search_propertytype);
$query ="SELECT p.* FROM $wpdb->posts p, $wpdb->postmeta p1 WHERE p.ID = p1.post_id AND (p1.meta_key='propertytype_value' AND p1.meta_value='$search_propertytype' OR p1.meta_key='propertytype2_value' AND p1.meta_value='$search_propertytype')";
$sptt = getIds( $query );
$_ids = ( !empty($sptt) ? ( !empty($_ids) ? array_intersect( $_ids, $sptt) : "" ) : "" );
}
}

I made a solution by WP_Query and custom meta box. Made my query argument as following:
$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'NOT LIKE'
),
array(
'key' => 'price',
'value' => array( 20, 100 ),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
);
$query = new WP_Query( $args );
Check wordpress official document: http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
You can check in this way. May be it can help. Thanks.

Related

How to add custom fields to WooCommerce product data panel

I have created a custom product type for events in WooCommerce. Now I want to add some custom fields to it.
This can be achieved with functions like woocommerce_wp_select(), woocommerce_wp_text_input() etc. However, as far as I know, whith these function you can only add text input fields, textarea's, select boxes and select dropdowns.
I want to add a date picker field, a file upload field and an url input field.
I have created these fields and they do render on the admin panel as they should, but the values are not saved (although I'm using the action hook 'woocommerce_process_product_meta'). Only the first 2 fields (event_type and event_location), which are created with the WooCommerce function, are stored properly.
What am I doing wrong here?
My code:
add_action('woocommerce_product_data_panels', 'okappi_add_custom_fields');
function okappi_add_custom_fields()
{ ?>
<div id="event_details" class="panel woocommerce_options_panel hidden">
<div class="options_group" class="show_if_event">
<? woocommerce_wp_select([
'id' => 'event_type',
'label' => __('Event type', 'custom'),
'wrapper_class' => 'show_if_event',
'value' => get_post_meta(get_the_ID(), 'event_type', true),
'options' => array('online' => 'Online', 'international' => 'International', 'internal' => 'Internal'),
]); ?>
<? woocommerce_wp_text_input([
'id' => 'event_location',
'label' => __('Event location', 'custom'),
'wrapper_class' => 'show_if_event',
'value' => get_post_meta(get_the_ID(), 'event_location', true),
]); ?>
<p class="show_if_event form-field event_start_date_field">
<label for="event_start_date">Start date</label>
<input type="date" id="event_start_date" name="event_start_date" class="date short">
</p>
<p class="show_if_event form-field event_end_date_field">
<label for="event_end_date">End date</label>
<input type="date" id="event_end_date" name="event_end_date" class="date short">
</p>
<p class="show_if_event form-field event_pdf_field">
<label for="event_pdf">PDF upload</label>
<input type="file" id="event_pdf" name="event_pdf" class="date short">
</p>
<p class="show_if_event form-field event_link_field">
<label for="event_link">Event link</label>
<input type="url" id="event_link" name="event_link" class="date short" placeholder="https://www.my-event.com/">
</p>
</div>
</div>'
<? }
add_action('woocommerce_process_product_meta', 'save_custom_fields');
function save_custom_fields($post_id)
{
$product = wc_get_product($post_id);
$event_type = isset($_POST['event_type']) ? $_POST['event_type'] : '';
$product->update_meta_data('event_type', sanitize_text_field($event_type));
$event_location = isset($_POST['event_location']) ? $_POST['event_location'] : '';
$product->update_meta_data('event_location', sanitize_text_field($event_location));
$event_start_date = isset($_POST['event_start_date']) ? $_POST['event_start_date'] : '';
$product->update_meta_data('event_start_date', sanitize_text_field($event_start_date));
$event_end_date = isset($_POST['event_end_date']) ? $_POST['event_end_date'] : '';
$product->update_meta_data('event_end_date', sanitize_text_field($event_end_date));
$event_pdf = isset($_POST['event_pdf']) ? $_POST['event_pdf'] : '';
$product->update_meta_data('event_pdf', sanitize_text_field($event_pdf));
$event_link = isset($_POST['event_link']) ? $_POST['event_link'] : '';
$product->update_meta_data('event_link', sanitize_text_field($event_link));
$product->save();
}

wp_insert_post not adding category

I'm building a WordPress theme where people can submit posts using wp_insert_post. The code below adds the post title but does not add the category specified by the user. Instead it puts it in uncategorized.
How do I get it to add the new category to the post when submitted?
if(isset($_POST['new_post']) == '1') {
$post_title = $_POST['post_title'];
$new_cat_ID = $_POST['category'];
//Checking if category already there
$cat_ID = get_cat_ID( $_POST['newcat'] );
//If not create new category
if($cat_ID == 0) {
$cat_name = array('cat_name' => $_POST['newcat']);
wp_insert_category($cat_name);
}
//Get ID of newly created category
$new_cat_ID = get_cat_ID($_POST['newcat']);
// Create post object
$new_post = array(
'ID' => '',
'post_title' => $post_title,
'post_status' => 'publish',
'post_author' => $user->ID,
'tax_input' => array( 'category' => $new_cat_ID )
);
// Insert the post into the database
$post_id = wp_insert_post($new_post);
// This will redirect you to the newly created post
$post = get_post($post_id);
wp_redirect( home_url() );
exit;
}
Here's the HTML for the form:
<form style="" action="" method="post" id="foo">
<input type="hidden" name="new_post" value="1"/>
<input type="text" name="post_title" value="title" id="input-title"/>
<input type="text" name="category" value="apples" id="category" />
<input type="submit" value="Login">
</form>
The category input should be:
<input type="text" name="newcategory" value="apples" id="category" />
In my tests, wp_insert_category did not work and wp_insert_term had to be used (as per this forum thread).
Your wp_redirect is not taking where you thing it does. The section //This will redirect you to the newly created post is plain wrong.
The following is a working example with a security layer added with wp_nonce_field, but you must add User Input Data Validation.
Also, I'm testing while logged in, so it works. Your code does not take care of $user->ID, research for get_current_user to get this right.
<?php
if ( isset( $_POST['noncename_so_17539370'] ) && wp_verify_nonce( $_POST['noncename_so_17539370'], 'nonce_so_17539370' ) )
{
if( isset($_POST['new_post']) == '1' ) {
//Checking if category already there
$cat_ID = get_cat_ID( $_POST['newcat'] );
//If not create new category
if( !$cat_ID ) {
$arg = array( 'description' => "my description", 'parent' => 0 );
$cat_ID = wp_insert_term($_POST['newcat'], "category", $arg);
}
// Create post object
$new_post = array(
'ID' => '',
'post_title' => $_POST['post_title'],
'post_status' => 'publish',
//'post_author' => $user->ID,
'tax_input' => array( 'category' => $cat_ID )
);
// Insert the post into the database
$post_id = wp_insert_post($new_post);
// This will redirect you to the newly created post
$post = ;
wp_redirect( get_permalink( $post_id ) );
exit;
}
} else {
echo 'ERROR';
}
?>
<form style="" action="" method="post" id="foo">
<?php wp_nonce_field( 'nonce_so_17539370', 'noncename_so_17539370' ); ?>
<input type="hidden" name="new_post" value="1"/>
<input type="text" name="post_title" value="title" id="input-title"/>
<input type="text" name="newcat" value="apples" id="category" />
<input type="submit" value="Login">
</form>

WordPress Radio Boxes - selects only the last one

So I have a form as shown bellow. its a bit long. It contains three radio boxes. Every time I select one, doesn't matter which, and then hit submit, the last radio element shows up as selected instead of the one I clicked. I var dump the option (in this case aisis_core['display_rows']) and it will say the value of the radio element i selected instead of the current on selected.
So I select lists, it will show lists but the radio box selected is no_posts. Can some one tell me what I am doing wrong?
<form action="options.php" method="post">
<input type='hidden' name='option_page' value='aisis_options' /><input type="hidden"
name="action" value="update" /><input type="hidden" id="_wpnonce" name="_wpnonce"
value="f0385965c6" /><input type="hidden" name="_wp_http_referer" value=
"/WordPressDev/wp-admin/admin.php?page=aisis-core-options&settings-updated=true" />
<fieldset>
<div class="control-group">
<label class="radio"><input type="radio" id="rows" class="display" name=
"aisis_core[display_rows]" value="display_rows" checked="checked" /> Display
posts as rows. </label>
<div class="control-group">
<label class="radio"><input type="radio" class="display" name=
"aisis_core[display_rows]" value="list" checked="checked" /> Display posts a
list. </label>
</div>
<div class="control-group">
<label class="radio"><input type="radio" id="noDisplay" class="display" name=
"aisis_core[display_rows]" value="no_posts" checked="checked" /> Display no
posts.</label>
<div class="no_posts_section borderBottom">
<div class="well headLine">
<h1>Display No Rows</h1>
<p>If you choose to display no rows please give me a url of the page or
content you would like to display instead.</p>
<p class="text-info"><strong>Note:</strong> Formatting of said content is
up you. All we do is display it.</p>
</div>
<div class="control-group">
<div class="controls">
<input type="url" name="aisis_core[index_page_no_posts]" value=
"http://google.ca" placeholder="Url" />
</div>
</div>
</div>
<div class="control-group">
<div class="form-actions">
<input type="submit" class="btn btn-primary btn-large" />
</div>
</div>
</div>
</div>
</fieldset>
</form>
The function I am using from wordpress is:
checked('radio_box_value', isset($options['display_rows']), false)
Note: radio_box_value is replaced with what ever the value of the radio box is.
In this case only the last radio box has the "checked" in it's tag, when it should be which ever one I chose.
How are the elements being created?
The following is how I create the elements, they print out what you see above in the html for the radio buttons. These are done similar to, but not exactly, zend framework.
Its pretty straight forward what were doing, create the element, add the options to the element and then return it.
I hope this gives a better picture as to how these are being created.
protected function _radio_rows_element(){
$options = get_option('aisis_core');
echo $options['display_rows'];
$radio_element = array(
'name' => 'aisis_core[display_rows]',
'value' => 'display_rows',
'class' => 'display',
'id' => 'rows',
'checked' => checked('display_rows', isset($options['display_rows']) && $options['display_rows'] == 'display_rows', false),
'label' => ' Display posts as rows. <a href="#radioRows" data-toggle="modal">
<i class="icon-info-sign"> </i></a>'
);
$radio = new CoreTheme_Form_Elements_Radio($radio_element, $this->sub_section_rows_array());
return $radio;
}
protected function _radio_list_element(){
$options = get_option('aisis_core');
echo $options['display_rows'];
$radio_element = array(
'name' => 'aisis_core[display_rows]',
'value' => 'list',
'class' => 'display',
'checked' => checked('list', isset($options['display_rows']) && $options['display_rows'] == 'list', false),
'label' => ' Display posts a list. <a href="#radioLists" data-toggle="modal">
<i class="icon-info-sign"> </i></a>'
);
$radio = new CoreTheme_Form_Elements_Radio($radio_element);
return $radio;
}
protected function _radio_no_posts_element(){
$options = get_option('aisis_core');
echo $options['display_rows'];
$radio_element = array(
'name' => 'aisis_core[display_rows]',
'value' => 'no_posts',
'class' => 'display',
'id' => 'noDisplay',
'checked' => checked('no_posts', isset($options['display_rows']) && $options['display_rows'] == 'no_posts', false),
'label' => ' Display no posts.</a>'
);
$radio = new CoreTheme_Form_Elements_Radio($radio_element, $this->_sub_section_now_posts_array());
return $radio;
}
"checked" function seems to need the value as second parameter as is explained here http://codex.wordpress.org/Function_Reference/checked
Try like this:
protected function _radio_rows_element(){
$options = get_option('aisis_core');
echo $options['display_rows'];
$radio_element = array(
'name' => 'aisis_core[display_rows]',
'value' => 'display_rows',
'class' => 'display',
'id' => 'rows',
'checked' => checked('display_rows', (isset($options['display_rows']))?$options['display_rows']:'', false),
'label' => ' Display posts as rows. <a href="#radioRows" data-toggle="modal">
<i class="icon-info-sign"> </i></a>'
);
$radio = new CoreTheme_Form_Elements_Radio($radio_element, $this->sub_section_rows_array());
return $radio;
}
protected function _radio_list_element(){
$options = get_option('aisis_core');
echo $options['display_rows'];
$radio_element = array(
'name' => 'aisis_core[display_rows]',
'value' => 'list',
'class' => 'display',
'checked' => checked('list',(isset($options['display_rows']))?$options['display_rows']:'', false),
'label' => ' Display posts a list. <a href="#radioLists" data-toggle="modal">
<i class="icon-info-sign"> </i></a>'
);
$radio = new CoreTheme_Form_Elements_Radio($radio_element);
return $radio;
}
protected function _radio_no_posts_element(){
$options = get_option('aisis_core');
echo $options['display_rows'];
$radio_element = array(
'name' => 'aisis_core[display_rows]',
'value' => 'no_posts',
'class' => 'display',
'id' => 'noDisplay',
'checked' => checked('no_posts', (isset($options['display_rows']))?$options['display_rows']:'', false),
'label' => ' Display no posts.</a>'
);
$radio = new CoreTheme_Form_Elements_Radio($radio_element, $this->_sub_section_now_posts_array());
return $radio;
}
This will not give warning when isn't declared the variable $options['display_rows'] (that as you said is a possibility in your case) and will pass the value to the WordPress function to compare with.
You'll want to check the value in the checked condition, not you're just checking if any value is being selected, which is always true after a submit
change
checked('display_rows', isset($options['display_rows']), false)
to:
checked('display_rows', isset($options['display_rows']) && $options['display_rows'] == 'display_rows', false),
and for the list to:
checked('display_rows', isset($options['display_rows']) && $options['display_rows'] == 'list', false),
I did manage to write this:
public function set_element_checked($value, $option, $key){
$options = get_option($option);
if(isset($options[$key]) && $options[$key] == $value){
return 'checked';
}
}
which does exactly what I want. compare the element value to that of the $option[$key] and if they match return checked. can be called via:
'checked' => set_element_checked('display_rows', 'aisis_core', 'display_rows');

wp_query not filtering tax_query correctly in pre_get_posts

I'm having a problem with the following situation: I am creating a custom form for searching my custom post type (immobiliare) and attached to this I have 2 custom taxonomies: location and tipologia.
My searchform.php is:
<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
<input type="hidden" value="proceed" name="s" id="s" />
<fieldset>
<legend>Ricerca per:</legend>
<label class="screen-reader-text" for="query">Testo:</label>
<input type="text" value="<?php the_search_query(); ?>" name="query" id="query" />
</fieldset>
<fieldset>
<label class="screen-reader-text" for="s">Tipologia:</label>
<?php wp_dropdown_categories(array(
'hide_empty' => 0,
'taxonomy' => 'tipologia',
'name' => 'tipologia',
'show_option_all' => 'Nessuna Preferenza'
)); ?>
</fieldset>
<fieldset>
<label class="screen-reader-text" for="s">Località:</label>
<?php wp_dropdown_categories(array(
'hide_empty' => 0,
'taxonomy' => 'location',
'name' => 'location',
'show_option_all' => 'Nessuna Preferenza'
)); ?>
</fieldset>
<input type="submit" id="searchsubmit" value="Search" />
</form>
As you can see, I have 3 fields: 1 is a textfield and the other 2 are dropdowns with my taxonomies. I want the user to be able to search for these fields. I had to hack the "s" input type because it would not let me submit empty queries and added a "query" field instead.
My functions.php file is as follows:
<?php
// Start LOGGING
if(!function_exists('_log')){
function _log( $message ) {
if( WP_DEBUG === true ){
if( is_array( $message ) || is_object( $message ) ){
error_log( print_r( $message, true ) );
} else {
error_log( $message );
}
}
}
}
// end LOGGING
// start SEARCH FORM
function ij_get_int($var){
if (isset($var)) {
$int_var = intval($var);
if ($int_var > 0)
return $int_var;
}
return false;
}
function ij_get_str($var) {
$str_var = esc_attr($var);
if (strlen($str_var) > 0)
return $str_var;
return false;
}
function custom_search_results($query) {
if ($query->is_search && $query->is_main_query()) {
$tax_query = array(
'relation' => 'AND',
);
$location = ij_get_int($_GET['location']);
$tipologia = ij_get_int($_GET['tipologia']);
if ($location) {
array_push($tax_query, array(
'taxonomy' => 'location',
'field' => 'id',
'terms' => $location,
'operator' => 'IN'
));
}
if ($tipologia) {
array_push($tax_query, array(
'taxonomy' => 'tipologia',
'field' => 'id',
'terms' => $tipologia,
'operator' => 'IN'
));
}
$query->set('tax_query', $tax_query);
$query->set('s', ij_get_str($_GET['query']));
$query->set('post_type', 'immobiliare');
}
}
add_action('pre_get_posts', 'custom_search_results');
// end SEARCH FORM
?>
Here I hook into the response of my custom form and add:
The actual query ("query" and not "s"), when the user inputs valid data.
The filter by taxonomy, when needed.
I have no clue why this is not working out (spent a day!), I can see my query coming back with the correct 's' parameter:
$query->set('s', ij_get_str($_GET['query']));
but not the taxonomy filter.
What am I doing wrong? I want to use the standard Loop in my search.php file, so in some way I want my hook function to get automatically plugged into the loop. One curious thing is that if I create a new WP_Query object with the same setup (and not use the "set" method) it returns exactly what I want! I tried doing $query = new WP_Query... but this is not working too!!
If I dump the query request on the top of my search.php I get the following:
SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts WHERE 1=1 AND 0 = 1 AND (((wp_posts.post_title LIKE '%vil%') OR (wp_posts.post_content LIKE '%vil%'))) AND wp_posts.post_type = 'immobiliare' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10
Does anyone have any hints to share? You would be really cool to give me a hand!
Thanks
Dan
You probably solved this by now, but your query has ... where 1=1 and 0=1 ... so it wouldn't return anything since you are asking for a record set of items both true and false.

How do I create an array of form fields?

I'm writing a custom module and I am trying to create an array of form fields, but it doesn't seem it is what I am doing.
Here's the code I'm trying to use:
for($i = 0; $i < 3; $i++) {
$form['contact'][$i]['value'] = array(
'#type' => 'textfield',
'#title' => 'Contact Name',
'#size' => 50,
);
}
Doing this, I was expecting the form to print the field as:
<input type="text" value="" size="50" name="contact[0][value]" />
<input type="text" value="" size="50" name="contact[1][value]" />
<input type="text" value="" size="50" name="contact[2][value]" />
Instead, it outputs:
<input type="text" value="" size="50" name="0" />
<input type="text" value="" size="50" name="1" />
<input type="text" value="" size="50" name="2" />
Actually, all you need is to do this, but keep in mind this also changes how the values get returned in your form submit functions (you'll get a nested array rather than separate values in $form_state['values']).
$form['contact']['#tree'] = TRUE;
The answer provided is exactly what i needed. This is my code, which will probably help future developers.
$form['results']['subject'] = array(
'#tree' => TRUE
);
foreach($subjectList as $subject) {
$form['results']['subject'][$subject->id] = array(
'#type' => 'textfield',
'#title' => $subject->name,
'#maxlength' => 3,
'#required' => TRUE,
);
}

Resources