Skip Navigation

[Resolved] I've found an issue with a previous solution to a different ticket

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.

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)

This topic contains 9 replies, has 2 voices.

Last updated by daveG-7 1 year, 7 months ago.

Assisted by: Waqar.

Author
Posts
#2616235

A while ago, you provided a solution to my issue in this support ticket: https://toolset.com/forums/topic/add-default-text-to-multiselect-taxonomy-filters/

You provided the following code:

document.addEventListener("DOMContentLoaded", function() {
// Get the select element
const selectElement = document.querySelector('select[name="wpv-offering[]"]');

// Create a new option element
const defaultOption = document.createElement('option');
defaultOption.value = 'any';
defaultOption.text = 'Any';

// Set the new option as the default selected option
defaultOption.selected = true;

// Add the new option to the beginning of the select element
selectElement.insertBefore(defaultOption, selectElement.firstChild);
});

What I wanted was to was add "Any" as the default option for a multi-select taxonomy search, like you can for a multi-select field search. The solution you provided appeared to work - the term "Any" was added and was selected, so I thought this worked.

However, we just discovered an issue with this solution. The term "Any" is now an option that is automatically being searched for, but, of course, we don't have any objects with the taxonomy value of "Any" so no search results occur when that's selected and another search term is added to the search. This is because the term added says "Any" but doesn't act like any - it just acts like another taxonomy term. Is it possible to modify the code so that the value "any" that's set means any of the other values?

#2616353

Hi,

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

I'll suggest a few changes to that script, to overcome this.

1. The default option should have the empty value instead of 'any'.
2. The default option should be added but it shouldn't be in a 'selected' state.

Here is how the code will look after these changes:


document.addEventListener("DOMContentLoaded", function() {
    // Get the select element
    const selectElement = document.querySelector('select[name="wpv-location[]"]');
 
    // Create a new option element
    const defaultOption = document.createElement('option');
    defaultOption.value = '';
    defaultOption.text = 'Any';
 
    // Add the new option to the beginning of the select element
    selectElement.insertBefore(defaultOption, selectElement.firstChild);
});

I hope this helps and please let me know if you need further assistance.

regards,
Waqar

#2616545

That code triggers an error: Uncaught TypeError: Cannot read properties of null (reading 'insertBefore')
at HTMLDocument.<anonymous> ((index):1230:19)
(anonymous) @ (index):1230

Further, it won't accomplish my ultimate goal for this, which is having the Taxomomy multiselect match the appearance and functionality of the field multiselects on mobile. Without a selected option, on mobile the taxonomy multiselect shows "0 items" which is confusing for users.

You can see this by modifying the original code provided to set selected to false. Further, if I make the value empty, I still see the same error reported at the beginning - it's treating empty as a value and thus not returning items. Here's the modified code that shows that:

document.addEventListener("DOMContentLoaded", function() {
// Get the select element
const selectElement = document.querySelector('select[name="wpv-offering[]"]');

// Create a new option element
const defaultOption = document.createElement('option');
defaultOption.value = '';
defaultOption.text = 'Any';

// Set the new option as the default selected option
defaultOption.selected = false;

// Add the new option to the beginning of the select element
selectElement.insertBefore(defaultOption, selectElement.firstChild);
});

This inserts a non-selected Any option with a blank value, but when you select it to search, it returns no items. My theory is that the JS isn't written to deal with a blank value taxonomy item like it is with a blank value field item.

#2617001

Thanks for writing back.

The script was showing an error because the taxonomy multi-select name used on your website is 'wpv-offering', but the code that I shared in my last message had the name 'wpv-location'.
( as this is what I was using on my test website )

Your observation is correct and the way the taxonomy query filter works, if it encounters an empty value or a value for which a term is not found, the query returns no result.

To overcome this, here is what I'll recommend:

1. You'll need a custom function attached to the 'wpv_filter_query' filter, that will unset the taxonomy query filter for the specific taxonomy if a non-existent term is encountered for it.
( ref: https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query )

For example:


add_filter( 'wpv_filter_query', 'filter_empty_tax_custom_fn', 1000 , 3 );
function filter_empty_tax_custom_fn( $query_args, $view_settings ) {
	// check for a specific view
	if ( 	( !is_admin() && isset($view_settings['view_id'] ) ) && ( $view_settings['view_id'] == 12345 )  ) 
	{	
		// check if any taxonomy query filter is set
		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 'location'
				if ( $query_args['tax_query'][$i]['taxonomy'] == "offering") {
					// if no term is set 
					if ( $query_args['tax_query'][$i]['terms'] == 0 ) {
						// unset the query filter for this taxonomy
						unset($query_args['tax_query'][$i]);
					}
				}
			}
		}
	}
	return $query_args;
}

Note: You'll replace '12345' and 'offering' with your actual view's ID and the target taxonomy's slug, respectively.

The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through the active theme's "functions.php" file.

2. Here is the updated script that I'll recommend using. It is the same one as my last message, except for:

a). It uses the correct taxonomy field name 'wpv-offering', and
b). It will set the new default option as the selected option, but only if no other option is selected.
( because it doesn't makes sense to select the default 'Any' option when some other option or options are selected too )


document.addEventListener("DOMContentLoaded", function() {
	// Get the select element
	const selectElement = document.querySelector('select[name="wpv-offering[]"]');
	// Get the selected options
	var selectedOptions = document.querySelector('select[name="wpv-offering[]"]').selectedOptions;
	// Get the selected options values
	var selectedValues = Array.from(selectedOptions).map(({ value }) => value);

	// Create a new option element
	const defaultOption = document.createElement('option');
	defaultOption.value = '';
	defaultOption.text = 'Any';

	// Set the new option as the default selected option, only if no other option is selected
	if (selectedValues.length == 0) {
		defaultOption.selected = true;
	}

	// Add the new option to the beginning of the select element
	selectElement.insertBefore(defaultOption, selectElement.firstChild);
});

I hope this helps and for more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/

#2617065

Thank you so much for all your help on this - if you can't help any further, I'd understand.

However, this code doesn't quite seem to work. If I'm understanding the PHP code right, which I might not be, I feel that it's because you're running it if the terms in the filter are equal to 0, when what we should be running it based on would be if the selected term has a value of 0. The taxonomy offering is going to have lots of terms, so it wouldn't be set to 0 and wouldn't run.

The line in question is if ( $query_args['tax_query'][$i]['terms'] == 0 ) {

#2617263

> I feel that it's because you're running it if the terms in the filter are equal to 0, when what we should be running it based on would be if the selected term has a value of 0. The taxonomy offering is going to have lots of terms, so it wouldn't be set to 0 and wouldn't run.

- When the taxonomy filter encounters an empty value or a value for which a term is not found, it uses the value '0' in the query.
( it is the same case when the default 'Any' option is selected and we need to target )

This is the reason my code checks for the '0' value. When it is encountered it unsets the taxonomy query altogether, because we need all the results, irrespective of whether any term from this taxonomy is attached or not.

If you could share temporary admin login details, along with the link to the page with this view, I can take a look into why the code is not working.

Note: Your next reply will be private and making a complete backup copy is recommended before sharing the access details.

#2617399

Thanks. however, it doesn't seem like this response is set to private.

#2617549

I apologize for the inconvenience and I'm setting the next reply as private again.

Note: For access details, don't include them in the message area, and use the dedicated fields available for that.

#2617861

Thank you for sharing the access details.

The page that you shared was showing not found message. After some digging, I found the page 'Pastured Producer Guide' that is using the view 'Full Search'.
( it had the custom script added in the commented form )

I made the following changes and the code seems to be working:

1. I removed the comments around the custom script in the view.

2. The custom PHP code added in the Toolset's custom code section was missing the first line, which I've included now:


add_filter( 'wpv_filter_query', 'filter_empty_tax_custom_fn', 1000 , 3 );

3. The code was still using the dummy view ID '12345':


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

I've replaced it with the actual target view's ID '72439':


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

4. Also since the view was set to update the results through AJAX, that is without reloading the page, I further adjusted that same line to:


if (    ( isset($view_settings['view_id'] ) ) && ( $view_settings['view_id'] == 72439 )  ) 

#2618085

This fixes my issue - thanks for such incredible support - it was definitely above and beyond what was expected! It would be nice it this functionality was added to a future version of the Toolset plugins so taxonomy searches and field searches could behave the same out of the box. Thanks