Normally, OTA websites have a useful feature that is finding hotels by location. This feature is a filter using custom fields to filter hotels that meet the criteria the user needs. In this article, I will show you how to use custom fields and filter out hotels with custom fields that match the desired location.

Before Getting Started

In this article, we have to create a new custom post type for Hotel and custom taxonomy for Location for those hotels. To do it, let’s use the Meta Box plugin and its extensions:

  • Meta Box: a framework to create custom fields, custom post types, custom taxonomies. It’s free and available on wordpress.org;

Besides, in this example, I use a free theme as a demo, it’s Justread.

Step 1: Create a New Custom Post Type for Hotel and Custom Taxonomy for Location

I create a new custom post type named Hotel, and the information of each hotel is entered as a post of the Hotel post type. Besides, I create a custom taxonomy for this custom post type named Location, to enter information about the location of each hotel.

To create a new custom post type, go to Meta Box > Post Types > New Post Type. Then enter the information for the custom post type as the below picture.

Create a new custom post type for Hotel.

To create a taxonomy for location information, go to Meta Box > Taxonomies > Add New. In the entry for the custom taxonomy’s information, remember to choose Hotel in the Assign to Post Types section. This will assign the custom taxonomy that we’ve created to the Hotel post type.

Create a custom taxonomy for Location.

Now, the Hotel post type will appear on the admin menu. It includes a section to enter locations. Let’s go there and enter the information of a few hotels and locations. We need this data for the following steps.

Enter the information of a few hotels and locations.

Note: In this article, I just enter a few locations as an example. In fact, you have to enter a large number of locations which are on many levels such as countries, provinces, cities, regions, … That time, you need to import data to the Location taxonomy.

Import data to the Location taxonomy.

You can use plugins to easily import data. On wordpress.org, there’re many plugins to do it, you can refer here. It’s quite easy so I won’t mention it in detail here.

Step 2: Create a Search Button for Searching Hotels by Location

First, go to the archive page of the Hotel post type’s articles (it’s normally in http://domain.com/post-type-name).

This time, there‘s no search box on the page to filter hotels by a certain standard. So I add a box to search by location as follows:

Create a file named archive-hotel.php (the file name is in the form of archive- [post-type-name].php) in the theme folder and add the following code to the file:

<div class="filter-hotel">
<p>Search Hotel</p>
    <input class="filter-input" id="location" type="" name="" placeholder="Location">
    <input class="filter-action" type="submit" name="" value="Search">
</div>

You will see the search box as follows:

Create a search button for searching hotel by locations.

Step 3: Display Hotels that Meet the Criterion

I want that when users click the Search button, the page won’t reload, so I use ajax to filter.

I add the following code to the functions.php file:

function justread_custom_scripts() {
    $terms = get_terms( array(
        'taxonomy'   => 'location',
        'hide_empty' => false,
    ) );
    foreach ( $terms as $term ) {
        $location[] = $term->name;
    }
    $object = [
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'location_autocomplete' => $location,
    ];

    wp_enqueue_script( 'justread-ajax-filter-hotel', get_stylesheet_directory_uri() . '/js/filter-hotel.js', array( 'jquery' ), '', true );
    wp_localize_script( 'justread-ajax-filter-hotel', 'ajax_object', $object );
}
add_action( 'wp_enqueue_scripts', 'justread_custom_scripts' );

Explanation:

  • 'wp_enqueue_scripts': it’s the hook used to declare filter-hotel.js file that I‘ll create later;
  • wp_localize_script: a function that helps transfer the value of the variable 'ajax_url' from the functions.php file to the filter-hotel.js file.

Next, to get the data of the custom post type and return it as the form of json (it means showing the articles in the Hotel post type) when someone hit the Search button, add the following code to the functions.php file:

function justread_filter_hotel() {
    $location = $_POST['location'];
    $query_arr = array(
        'post_type' => 'hotel',
        'post_status' => 'publish',
        'tax_query' => array(
            array(
                'taxonomy' => 'location',
                'field'    => 'name',
                'terms'    => array( $location ),
                'operator' => 'IN',
            ),
        ),
    );
    $query = new WP_Query( $query_arr );

    if ( $query->have_posts() ) :
        ob_start();
        while ( $query->have_posts() ) : $query->the_post();
            get_template_part( 'template-parts/content', get_post_format() );
        endwhile;
        $posts = ob_get_clean();
    else :
        $posts = '<h1>' . __( 'No post', 'justread' ) .'</h1>';
    endif;

    $return = array(
        'post' => $posts,
    );
    wp_send_json( $return );
}
add_action( 'wp_ajax_justread_filter_hotel', 'justread_filter_hotel' );
add_action( 'wp_ajax_nopriv_justread_filter_hotel', 'justread_filter_hotel' );

Explanation:

  • 'hotel': the slug of the custom post type that we created in step 1;
  • 'location': the ID of the custom taxonomy that we created in step 1 for the location;
  • 'wp_ajax_justread_filter_hotel' and 'wp_ajax_nopriv_justread_filter_hotel': they’re two hooks to perform ajax. They’re named according to the following rule: wp_ajax_my_action and wp_ajax_nopriv_my_action. In this example, my_action is justread_filter_hotel.

Also in the theme folder, let’s create another file named filter-hotel.js with the following content:

jQuery( function ( $ ) {
    function filterHotel() {
        var location = ajax_object.location_autocomplete;
        $( '#location' ).autocomplete({
            source: location
        });

        $( '.filter-action' ).on( 'click', function() {
            var location = $( '#location' ).val();
            jQuery.ajax({
                url: ajax_object.ajax_url,
                type: "POST",
                data: {
                    action: 'justread_filter_hotel',
                    location: location,
                },
                success: function(response) {
                    $( '.site-main' ).html(response.post);
                }
            });
        } );
    }
    filterHotel();
} );

In the above code, I have used the autocomplete library of the jquery so that when a user types any character into the search box (Search), the similar locations will be suggested.

When typing any character, the similar locations will be suggested.

This whole js file will help get the location data when the user clicks on the Search button, then passes to the functions.php file to retrieve the data of the posts in the Hotel post type. Then, when the functions.php file returns the data, the js file will display them (thanks to the $ ('.site-main') .html (response.post); code).

Now, when you enter a location in the Search box, only the hotels in that location will be returned and displayed on the page.

So you've finished creating filters to search for hotels by location already.

Last Words

By this way, you can create similar filters to search for hotels or posts by any criteria that we’ll explore in the upcoming article. You can apply it flexibly to create more filtering features for your website.

Hopefully, this tip can help you build an OTA website easier. If you have any questions or suggestions, leave a comment below. And do not forget to follow my next tutorials!

Leave a Reply

Your email address will not be published. Required fields are marked *