Support » Developing with WordPress » Custom Search Form, CPT, Multiple Text inputs

  • Resolved bengrzy

    (@bengrzy)


    I have been working on creating a custom search form for a legal directory. I have a custom post type with 3 custom taxonomies. Some of these taxonomies have multiple words in them and that seems to be where my problem is.

    I’m struggling to get the search to perform correctly when there is a taxonomy being searched for that has multiple words, for example, “accident reconstruction and safety” produces a “page not found” error, and from what I have gathered this is because WordPress does not allow for spaces in a search? Some taxonomies such as “law” (single word) work just fine.

    I originally tried following this guide: https://www.smashingmagazine.com/2016/03/advanced-wordpress-search-with-wp_query/ from smashing magazine, however I could not get the pre_get_posts action hook to function properly, it ran every time a page was loaded and I could not get it to ever pick up on the parameters set in the input fields. So I abandoned that.

    Then I was trying to use get_search_query() in the value attribute of the input fields on my custom search form (there are 3 of them) but I could find a way to replace spaces with dashes and ultimately this was failing as well.

    Example of an input field with get_search_query()

            <div class="inputGroup inputGroup_specality">
                <label for="search__specality" class="label">Specalities</label>
                <input type="text" name="experts_specialities" value="<?php get_search_query() ?>" class="input" id="search__specality" placeholder="Ex: Specalities">
                <div class="searchResults" id="searchResults_specality"></div>
            </div>

    Next, I created a JS functions that listened for input and then replaced spaces with dashes and removed uppercase letters, and then set this new string as a value attribute, but when I tested this. While checking the console I verfied that it was updating the value attribute in the input fields however the search did not honor the attribute value but instead used the actual value in the input field.

    Here is the custom search form code

    <form role="search" action="<?php echo home_url( '/' ); ?>" method="get" class="expert_searchForm" autocomplete="off">
    <input type="hidden" name="post_type" value="experts" />
        <div class="searchForm__inputs">
            <div class="inputGroup inputGroup_industry">
                <label for="search__industry" class="label">Industries</label>
                <input type="text" onfocusout="getValue('search__industry')" name="experts_industries" value="" class="input" id="search__industry" placeholder="Ex: Medical failure, Accident Analysis">
                <div class="searchResults" id="searchResults_industry"></div>
            </div>
            <div class="inputGroup inputGroup_specality">
                <label for="search__specality" class="label">Specalities</label>
                <input type="text" name="experts_specialities" value="" class="input" id="search__specality" placeholder="Ex: Specalities">
                <div class="searchResults" id="searchResults_specality"></div>
            </div>
            <div class="inputGroup inputGroup_location">
                <label for="search_location" class="label">City</label>
                <input type="text" name="experts_locations" value="" class="input" id="search__location" placeholder="City, County or State">
                <div class="searchResults" id="cityResults"></div>
            </div>
            <input type="submit" class="input input_button" id="search__button" value="Search">
        </div>
        <div class="searchResults" id="searchResults"></div>
    </form>

    Here is the JS function I came up with to create search friendly strings

    	function getValue (taxonomy) {
    		let tax = document.getElementById(taxonomy).value;
    		let newTax = tax.replace(/\s+/g, '-').toLowerCase();
    		document.getElementById(taxonomy).setAttribute('value', newTax);
    		return 'nice';
    	}

    Any help would be wildly appreciated.

    Thanks.

    • This topic was modified 1 year ago by bengrzy.
Viewing 5 replies - 1 through 5 (of 5 total)
  • Joy

    (@joyously)

    It sounds like you are trying to do something different from what that article was doing. Yours sounds like you want to search for text in the taxonomy term names, and that’s not what the WP search is for at all.
    Can you briefly state what you are trying to do?

    Thread Starter bengrzy

    (@bengrzy)

    I have a custom post type, Experts, it has 3 taxonomies associated with it, Specialties, Industries, and Location. Some of those taxonomies have multiple words in them, the search works as expected when there the taxonomy only contains a single word.

    The form has 3 input fields that are intended to search each of the taxonomies, I have some javascript guessing the exact names of each taxonomy, the intention is that a user can then select the one they are looking for. All it needs to do is search the names of the taxonomy, however as I said before it’s not working properly when there are multiple words in the taxonomy name.

    Can you explain what you mean by “that’s not what the WP search is for at all” the article I referenced is a tutorial that creates a custom search form that searches a CPT and its taxonomy, which is basically exactly what I’m trying to do. The biggest difference being the article’s CPT has a single custom Taxonomy where mine has 3…

    Joy

    (@joyously)

    The article does not use the search input (s) to find a taxonomy name. s is for the WP search, and it searches the title and content.
    The article uses the pre_get_posts filter to generate a tax_query parameter for the main query.

    Thread Starter bengrzy

    (@bengrzy)

    The issue I was running into with pre_get_posts is that it runs every time a page is loaded regardless of whether the form was filled out or submitted at all.

    Idk, I’ll just use a plugin I guess. Oh well.

    Thread Starter bengrzy

    (@bengrzy)

    I ended up coming up with a solution to my problem that did not require any plugin. Maybe it could be of help to someone in the future.

    I found that there is an HTML input element with built-in datasets that allow a user to type in what they are searching for and then it will automatically filter the items in the dataset, the dataset is displayed as a dropdown below the input field.

    I created a custom function that uses a custom query to gather each custom taxonomy type, and then dynamically creates the HTML input/dataset elements

    function create_taxonomy_select($tax) {
        $args = array( 'hide_empty' => false );
        $industries = get_terms($tax, $args);
        $tax_name = ucfirst(str_replace("experts_", "", $tax));
        $select_industry = '<input class="tax-list" id="'. $tax .'-container" list="' . $tax . '" placeholder="Search By '. $tax_name .'">';
        $select_industry .= '<datalist id="' . $tax . '">';
        foreach ( $industries as $term ) {
                $select_industry .= '<option data-value="' . $term->slug . '">' . $term->name . '</option>';
            }
        $select_industry .= '</datalist>';
        $select_industry .= '<input type="hidden" name="' . $tax . '" id="' . $tax . '-hidden">';
        return $select_industry;
    }

    Then I built the container for the search form that uses the above function to create the taxonomy fields

    <div class="search-container">
    	<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
    		<img src="<?php echo esc_attr( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" data-height-percentage="<?php echo esc_attr( et_get_option( 'logo_height', '54' ) ); ?>" />
    	</a>
    <form role="search" action="<?php echo home_url( '/' ); ?>" method="get" class="expert_searchForm" autocomplete="off">
    <input type="hidden" name="post_type" value="experts" />
        <div class="searchForm__inputs">
        <?php 
            echo create_taxonomy_select('experts_industries');
        ?>
        <?php 
            echo create_taxonomy_select('experts_specialities');
        ?>
        <?php 
            echo create_taxonomy_select('experts_locations');
        ?>
            <input type="hidden">
            <input type="submit" class="input input_button" id="search__button" value="Search">
        </div>
        <div class="searchResults" id="searchResults"></div>
    </form>
    </div>

    Finally, I had to use a bit of javascript to get the search to work properly, WordPress uses the value attribute of the dataset items to perform searches, however, the dataset displays this attribute along with the name, the JS is a workaround so that a searchable value is used (no spaces, ampersands etc) basically it dynamically adds the value attribute using the data-value attribute, this attribute is not displayed by the dataset element.

    <script>
    
    document.addEventListener("DOMContentLoaded", function(){
        var inputs = document.getElementsByClassName('tax-list');
    
        for (i = 0; i < inputs.length; i++) {
            inputs[i].addEventListener('input', function(e) {
                var input = e.target,
                list = input.getAttribute('list'),
                hiddenInput = document.getElementById(list + '-hidden'),
                options = document.querySelectorAll('#' + list + ' option'),
                inputValue = input.value;
                for(var i = 0; i < options.length; i++) {
                    var option = options[i];
                    if(option.innerText === inputValue) {
                        hiddenInput.value = option.getAttribute('data-value');
                        break;
                    }
                }
            });
        }
    });
    </script>

    Anyhow, it works beautifully so far, and is exactly what I needed!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Custom Search Form, CPT, Multiple Text inputs’ is closed to new replies.