Skip Navigation

[Resuelto] Allow frontend user to change "any" to "all" – closed by mistake

This support ticket is created hace 6 años. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Hoy no hay técnicos de soporte disponibles en el foro Juego de herramientas. Siéntase libre de enviar sus tiques y les daremos trámite tan pronto como estemos disponibles en línea. Gracias por su comprensión.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

Este tema contiene 10 respuestas, tiene 2 mensajes.

Última actualización por Ido Angel hace 6 años.

Asistido por: Waqar.

Autor
Mensajes
#1152147

hey,

https://toolset.com/forums/topic/allow-frontend-user-to-change-any-to-all

sorry to reopen this, but it doesn't really work:

enlace oculto

it doesn't matter which opeiotn i choose, it always shows me "any" in the results...

any (no pun intended) idea?

thanks!
ido

#1152953

Hi Ido,

Thank you for contacting us and I'll be happy to assist.

I've checked your search form ( at enlace oculto ) and noticed a couple of things:

1. The view is set to update the results using AJAX. Since we're using custom code to filter the default query through "wpv_filter_query" and values passed in the URL parameters, it will only work when results are set to update on page reload when the search's submits button is clicked.

2. The code that was shared as an example was for a case when only single taxonomy filter's query relationship needs to be changed.

But on your form, I see 4 taxonomy terms filters and 4 custom select fields which are all using the same name "custom_query_type".

You'll need to update each field's custom select field with a unique name and then using the suggestions from my original message ( ref: https://toolset.com/forums/topic/allow-frontend-user-to-change-any-to-all/#post-1138189 ) print the query and update the code based on indexes for each taxonomy query separately.

I hope this clarifies and let me know if you need any further assistance around this.

regards,
Waqar

#1152988

Thx waqar!
Could you possibly give me an example for two different codes for two different fields?

#1153775

Hi Ido,

For 4 different taxonomy filters, your code will look similar to:


add_filter( 'wpv_filter_query', 'filter_cats_custom_fn', 1000 , 3 );
function filter_cats_custom_fn( $query_args, $view_settings ) {

	if ( !is_admin() && ( isset($view_settings['view_id']) && $view_settings['view_id'] == 138) ) {

		// check if there is any taxonomy filter was used
		if (  (!empty( $query_args['tax_query'])) ) {

			// run code for each tax query available
			for ($i=0; $i < (count($query_args['tax_query']) - 1) ; $i++) {

				// case for the taxonomy 1
				if ( $query_args['tax_query'][$i]['taxonomy'] == "category-slug-1") {

					$query_args['tax_query'][$i]['operator'] = $_GET['custom_query_type_1'];

					if ($_GET['custom_query_type_1'] == "IN") {
						$query_args['tax_query'][$i]['include_children'] = 1;
					} else {
						$query_args['tax_query'][$i]['include_children'] = '';
					}
				}

				// case for the taxonomy 2
				if ( $query_args['tax_query'][$i]['taxonomy'] == "category-slug-2") {
					$query_args['tax_query'][$i]['operator'] = $_GET['custom_query_type_2'];

					if ($_GET['custom_query_type_2'] == "IN") {
						$query_args['tax_query'][$i]['include_children'] = 1;
					} else {
						$query_args['tax_query'][$i]['include_children'] = '';
					}

				}

				// case for the taxonomy 3
				if ( $query_args['tax_query'][$i]['taxonomy'] == "category-slug-3") {
					$query_args['tax_query'][$i]['operator'] = $_GET['custom_query_type_3'];

					if ($_GET['custom_query_type_3'] == "IN") {
						$query_args['tax_query'][$i]['include_children'] = 1;
					} else {
						$query_args['tax_query'][$i]['include_children'] = '';
					}

				}

				// case for the taxonomy 4
				if ( $query_args['tax_query'][$i]['taxonomy'] == "category-slug-4") {
					$query_args['tax_query'][$i]['operator'] = $_GET['custom_query_type_4'];

					if ($_GET['custom_query_type_4'] == "IN") {
						$query_args['tax_query'][$i]['include_children'] = 1;
					} else {
						$query_args['tax_query'][$i]['include_children'] = '';
					}

				}
				
			}

		}
	}
	return $query_args;
}

Notes:
1. Please make sure all instances of "category-slug-1", "category-slug-2", "category-slug-3" & "category-slug-4" are updated to match your actual taxonomy slugs.

2. Likewise, please also make sure to update all instances of "custom_query_type_1", "custom_query_type_2", "custom_query_type_3" & "custom_query_type_4" match the actual custom select fields used in the forms.

3. You can always print the query ( ref: https://toolset.com/forums/topic/allow-frontend-user-to-change-any-to-all/#post-1138189 ) to see and troubleshoot, which part or segment of the code is working or not.

For a more personalized assistance around custom programming, you can also hire a professional from our list of recommended contractors:
https://toolset.com/contractors/

I hope this helps.

regards,
Waqar

#1153781

hey waqar - thanks for evething, i really appreciate this.
i changed the code like this:

<?php

function theme_enqueue_styles() {
    wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'avada-stylesheet' ) );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );

function avada_lang_setup() {
	$lang = get_stylesheet_directory() . '/languages';
	load_child_theme_textdomain( 'Avada', $lang );
}
add_action( 'after_setup_theme', 'avada_lang_setup' );


add_filter('show_admin_bar', '__return_false', 99);





add_filter( 'wpv_filter_query', 'filter_cats_custom_fn', 1000 , 3 );
function filter_cats_custom_fn( $query_args, $view_settings ) {
 
    if ( !is_admin() && ( isset($view_settings['view_id']) && $view_settings['view_id'] == 138) ) {
 
        // check if there is any taxonomy filter was used
        if (  (!empty( $query_args['tax_query'])) ) {
 
            // run code for each tax query available
            for ($i=0; $i < (count($query_args['tax_query']) - 1) ; $i++) {
 
                // case for the taxonomy 1
                if ( $query_args['tax_query'][$i]['taxonomy'] == "known-as") {
 
                    $query_args['tax_query'][$i]['operator'] = $_GET['custom_query_type_1'];
 
                    if ($_GET['custom_query_type_1'] == "IN") {
                        $query_args['tax_query'][$i]['include_children'] = 1;
                    } else {
                        $query_args['tax_query'][$i]['include_children'] = '';
                    }
                }
 
                // case for the taxonomy 2
                if ( $query_args['tax_query'][$i]['taxonomy'] == "genres") {
                    $query_args['tax_query'][$i]['operator'] = $_GET['custom_query_type_2'];
 
                    if ($_GET['custom_query_type_2'] == "IN") {
                        $query_args['tax_query'][$i]['include_children'] = 1;
                    } else {
                        $query_args['tax_query'][$i]['include_children'] = '';
                    }
 
                }
 
                // case for the taxonomy 3
                if ( $query_args['tax_query'][$i]['taxonomy'] == "wpcf-birth-country") {
                    $query_args['tax_query'][$i]['operator'] = $_GET['custom_query_type_3'];
 
                    if ($_GET['custom_query_type_3'] == "IN") {
                        $query_args['tax_query'][$i]['include_children'] = 1;
                    } else {
                        $query_args['tax_query'][$i]['include_children'] = '';
                    }
 
                }
 
                // case for the taxonomy 4
                if ( $query_args['tax_query'][$i]['taxonomy'] == "city") {
                    $query_args['tax_query'][$i]['operator'] = $_GET['custom_query_type_4'];
 
                    if ($_GET['custom_query_type_4'] == "IN") {
                        $query_args['tax_query'][$i]['include_children'] = 1;
                    } else {
                        $query_args['tax_query'][$i]['include_children'] = '';
                    }
 
                }
                 
            }
 
        }
    }
    return $query_args;
}

in the filter section, this is what i have (i changed the custom query name to match the code):

<h1 style="margin-top: 0;">מציג [wpv-items-count] ערכים מתוך [wpv-found-count] שנמצאו (עמוד <span id="current-page-number">[wpv-pager-current-page]</span> מתוך [wpv-pager-total-pages]):</h1>
<div class="entry-sorting">
  <span class="sort-title">מיון לפי: </span>[wpv-sort-orderby type="select" options="post_title,field-wpcf-year-of-birth,field-wpcf-year-of-death,field-wpcf-birth-country,field-wpcf-death-country" label_for_post_title="שם הערך" label_for_field-wpcf-year-of-birth="שנת לידה" label_for_field-wpcf-year-of-death="שנת פטירה" label_for_field-wpcf-birth-country="ארץ לידה" label_for_field-wpcf-death-country="ארץ פטירה" orderby_as_numeric_for="field-wpcf-year-of-birth,field-wpcf-year-of-death" orderby_ascending_for="post_title,field-wpcf-year-of-birth,field-wpcf-year-of-death,field-wpcf-birth-country,field-wpcf-death-country"][wpv-sort-order type="select" options="asc,desc" label_for_asc="Ascending" label_for_desc="Descending" label_asc_for_post_title="א - ת" label_desc_for_post_title="ת - א" label_asc_for_field-wpcf-year-of-birth="סדר עולה" label_desc_for_field-wpcf-year-of-birth="סדר יורד" label_asc_for_field-wpcf-year-of-death="סדר עולה" label_desc_for_field-wpcf-year-of-death="סדר יורד" label_asc_for_field-wpcf-birth-country="א - ת" label_desc_for_field-wpcf-birth-country="ת - א" label_asc_for_field-wpcf-death-country="א - ת" label_desc_for_field-wpcf-death-country="ת - א"]
</div>
[wpv-filter-start hide="false"]
[wpv-filter-controls]
<div class="form-group namer">
	<label>[wpml-string context="wpv-views"]שם:[/wpml-string]</label>
	<div class="nameinput">[wpv-filter-search-box placeholder="הקלידו לפחות 3 תווים..." output="bootstrap"][wpv-filter-submit name="" type="button" output="bootstrap" class="fas fa-search"]</div>
</div>
<div class="form-group">
	<label class="toggler knownas">[wpml-string context="wpv-views"]ידוע\ה כ:[/wpml-string]</label>
	<div class="open-search">[wpv-control-post-taxonomy taxonomy="known-as" type="checkboxes" format="%%NAME%% (%%COUNT%%)" url_param="wpv-known-as"]
        <select id="wpv_control_select_query_type" name="custom_query_type_1" class="js-wpv-filter-trigger form-control">
        <option value="IN">כל אחד מהערכים</option>
        <option value="NOT IN">אף אחד מהערכים</option>
        <option value="AND">כל הערכים</option>
    </select></div>
</div>
<div class="form-group">
	<label class="toggler gender">[wpml-string context="wpv-views"]מגדר[/wpml-string]</label>
	<div class="open-search withselect">[wpv-control-post-taxonomy taxonomy="gender" type="select" default_label="-- בחירה --" format="%%NAME%% (%%COUNT%%)" url_param="wpv-gender"]</div>
</div>
<div class="form-group">
	<label class="toggler genres">[wpml-string context="wpv-views"]ז'אנרים[/wpml-string]</label>
	<div class="open-search">[wpv-control-post-taxonomy taxonomy="genres" type="checkboxes" format="%%NAME%% (%%COUNT%%)" url_param="wpv-subjects-in-creations"]
        <select id="wpv_control_select_query_type" name="custom_query_type_1" class="js-wpv-filter-trigger form-control">
        <option value="IN">כל אחד מהערכים</option>
        <option value="NOT IN">אף אחד מהערכים</option>
        <option value="AND">כל הערכים</option>
    </select></div>
</div>
<div class="form-group">
	<label class="toggler yearofbirth">[wpml-string context="wpv-views"]שנת לידה[/wpml-string]</label>
	<div class="open-search withselect">[wpv-control-postmeta field="wpcf-year-of-birth" type="select" format="%%NAME%% (%%COUNT%%)" default_label="-- בין --" url_param="wpv-wpcf-year-of-birth_min"]
	[wpv-control-postmeta field="wpcf-year-of-birth" type="select" default_label="-- לבין --" url_param="wpv-wpcf-year-of-birth_max"]</div>
</div>
<div class="form-group">
	<label class="toggler yearofdeath">[wpml-string context="wpv-views"]שנת פטירה[/wpml-string]</label>
	<div class="open-search withselect">[wpv-control-postmeta field="wpcf-year-of-death" type="select" format="%%NAME%% (%%COUNT%%)" default_label="-- בין --" url_param="wpv-wpcf-year-of-death_min"]
	[wpv-control-postmeta field="wpcf-year-of-death" type="select" default_label="-- לבין --" url_param="wpv-wpcf-year-of-death_max"]</div>
</div>
<div class="form-group">
	<label class="toggler countryofbirth">[wpml-string context="wpv-views"]ארץ לידה[/wpml-string]</label>
	<div class="open-search">
	[wpv-control-postmeta field="wpcf-birth-country" type="checkboxes" format="%%NAME%% (%%COUNT%%)" url_param="wpv-wpcf-birth-country"]
        <select id="wpv_control_select_query_type" name="custom_query_type_3" class="js-wpv-filter-trigger form-control">
        <option value="IN">כל אחד מהערכים</option>
        <option value="NOT IN">אף אחד מהערכים</option>
        <option value="AND">כל הערכים</option>
    </select></div>
</div>
<div class="form-group">
	<label class="toggler cityofbirth">[wpml-string context="wpv-views"]ישוב לידה[/wpml-string]</label>
	<div class="open-search">[wpv-control-post-taxonomy taxonomy="city" format="%%NAME%% (%%COUNT%%)" type="checkboxes" url_param="wpv-city"]
        <select id="wpv_control_select_query_type" name="custom_query_type_4" class="js-wpv-filter-trigger form-control">
        <option value="IN">כל אחד מהערכים</option>
        <option value="NOT IN">אף אחד מהערכים</option>
        <option value="AND">כל הערכים</option>
    </select></div>
</div>
  <div class="search-buttons">
  [wpv-filter-reset reset_label="איפוס" output="bootstrap"]
  [wpv-filter-submit name="סינון" type="button" output="bootstrap"]  
</div>
[/wpv-filter-controls]
[wpv-filter-end]

and it's still not working.
i know 1 thing which is that i have 1 filter which isn't a taxonomy, but a custom field (wpcf-birth-country). is it the one wrecking the code?

#1154108

hey again,
i mentioned this earlier - but maybe this could be the issue:
wordpress doesn't allow me to save the functions.php file with this code. it says there is an error. only if i upload the file via ftp can i make the changes. otherwise it crashes, as if there's something wrong in the code.
thanks!
ido

#1155426

dear waqar - sorry for nagging, but you went such a long way to help me with this - can we please find the problem and fix it?
i'm summing up - we have a few issues:

1. the functions.php file won't update in the editor. i need to upload it manually to work. if i remove your code, it does update. could this be the problem preventing the code from working?
2. i have i filter (the country field) which is a custom field and not a taxonomy (it is this way because i need to sort with this field, and i can't sort with taxonomies). how do we go about that?
3. basically, i see the url parameter updating after i choose "NOT IN" to this:

enlace oculto

but the fact is that the results are not excluding the filter, but including it.

please let me know.
also - you can send me a link to a working example and i'll try figure things.
i really appreciate it!

cheers,
ido

#1155448

UPDATE: I think I got it to work!!!

I removed the custom field and entered only taxonomies.

The only thing is: could we keep the select box option showing the latest picked? for example, if i chose "not it", after page refreshed it would still show "not in"?

cheers!
ido

#1155579

Hi Ido,

Please accept my apologies for not able to follow up on this sooner.

Glad you were able to make the code work and yes, the suggested solution was intended for the taxonomy filters only, as indicated in the comments in the code.

If you'll print the actual query arguments for the query, by following my suggestion from the last message, you'll see that when both taxonomy and custom field filters are present in the query, two separate associative arrays are created.

The one with the taxonimies has the key "tax_query" and the one for the custom fields has the key "meta_query". You can extend the code example I shared earlier to filter the custom field filters as well.

As for your question around making the correct option selected, after the page refresh, you can create a custom shortcode for this:

1. Please add following code for the shortcode in the theme's "functions.php" file:


add_shortcode( 'get-field-paramter', 'get_field_paramter_func');
function get_field_paramter_func($atts){
	$parameter = $atts['parameter'];
	$value = $atts['value'];
	
	if (!empty($_GET[$parameter]) && $_GET[$parameter] == $value) {
		return "selected";
	}
}

This shortcode will accept two attributes "parameter" and the "value" and if the provided paramter will match the value from the URL, it will return text "selected", which will make the relevant select field, selected.

In your custom select fields you can use the shortcode, as shown in this example:


<div class="form-group">
    <label>[wpml-string context="wpv-views"]Query type[/wpml-string]</label>
    <select id="wpv_control_select_query_type" name="custom_query_type" class="js-wpv-filter-trigger form-control">
      <option value=""> Select </option>
        <option value="IN" [get-field-paramter parameter="custom_query_type" value="IN"]>any of the selected categories</option>
        <option value="NOT IN" [get-field-paramter parameter="custom_query_type" value="NOT IN"]>not one of the selected categories</option>
        <option value="AND" [get-field-paramter parameter="custom_query_type" value="AND"]>all of the selected categories</option>
    </select>
</div>

You can update all your custom select fields the same way.

This should do the trick.

regards,
Waqar

#1155607

Thank you Waqar!

I updated the last snippet to fit all 6 taxonomies by changing the "custom_query_type_x" to the name as appearing in the name="custom_query_type_2" - right?

<select id="wpv_control_select_query_type" name="custom_query_type_2" class="js-wpv-filter-trigger form-control">
        <option value="IN" [get-field-paramter parameter="custom_query_type_2" value="IN"]>כל אחד מהערכים</option>
        <option value="NOT IN" [get-field-paramter parameter="custom_query_type_2" value="NOT IN"]>אף אחד מהערכים</option>
        <option value="AND" [get-field-paramter parameter="custom_query_type_2" value="AND"]>כל הערכים</option>

seems to work!!
thanks for all the effort!

#1404815

Hey Waqar!
Sorry to "wake up sleeping dogs"...
There's a bug with this code.
I have two different taxonomies (which I have applied this code to) but in each taxonomy there are items with the same name.
For example:
1) taxonomy called "published at" with an item in it called "times"
2) taxonomy called "bibliography paper" with an item in it called "times"
When I choose one item in a certain taxonomy, and press search, a strange thing happens: checkboxes for both "times" items are checked, in both search filters - "published at" and "bibliography paper", even though I checked only one of them before the search.
My guess is the checkboxes are checked becasue of the item's appearance in the URL Parameter, and once it's there, it checks every occurance of it in the search form (and naturally messes the results).
Maybe this code ahs anything to do with it?

add_shortcode( 'get-field-paramter', 'get_field_paramter_func');
function get_field_paramter_func($atts){
    $parameter = $atts['parameter'];
    $value = $atts['value'];
     
    if (!empty($_GET[$parameter]) && $_GET[$parameter] == $value) {
        return "selected";
    }
}

here's a live example for searching "הארץ" item inside "published at" but getting it checked in both taxnomies:

enlace oculto

any idea how to get around this?

Thanks!!

Ido