Simple AJAX posts filter by category and publish date for WordPress

The first thing you need to do is to write some HTML for category and publish date select box. This can be added to a custom template or your home page index.php file.

Now, when we have HTML ready, we also need to show some latest blog posts.

Create a file called content-post.php in template-parts directory. If this directory doesn’t exist, then create it. We’ll be showing the title of the post and linking to it.

Add this JavaScript code to your theme’s javascript file. This code filters out the posts by category and publish date under AJAX. The request is sent to ajax_filterposts_handler PHP function, then response is delivered by JavaScript (jQuery).

Finally, the PHP part. Add this to your functions.php file.

How to create a jQuery autocomplete drop down in WordPress

The autocompletion allows users to select from a pre-populated list of suggestions as they type. There are a number of jQuery autocomplete plugins. I’ll create an autocomplete from the post titles and redirect to a blog post based on selected option value. I’ll use jQuery UI autocomplete since it’s already included in WordPress. You can find demo: here.

Firstly, we need to enqueue jQuery UI and autocomplete libraries.

Secondly, we need to add a simple textbox in the front-end. I’ll attach jQuery UI autocomplete to it. I added a shortcode to output HTML text input field.

Also, add some CSS to make it nicer.

Autocomplete dropdown

Lastly, we need to enable autocomplete on our text input field and define the data to use. The datasource is a JavaScript array and you can define whatever you want – posts, pages, WooCommerce products, users and so on. If you have a lot of posts, then you should load a JSON file as source. Some useful links to documentation: option source, event select.

You can move JavaScript code to an external file.

Also, you can customize the select drop down with _renderItem method.