Using AJAX in Wordpress: Creating a blog

WordPress blogs should be fun, inviting and a great user experience! So why not create an Ajax WordPress blog to stop bouncing your users around from page to page!

Guides
Using AJAX in WordPress: Setting up a blog featured image

If you are looking for how to setup an Ajax WordPress blog page you are in the right place! This guide will go through a beginner friendly way of setting up an Ajax blog homepage with filters, search and infinite scrolling. As well as a professional custom way of building an Ajax blog page using HTML, PHP & JS.

Contents

WordPress has always primarily been a tool to allow anyone to setup a blogging platform, looking to set up a WordPress site but don’t know where to start? check out our beginner’s guide! It’s got a great name a that for a number of reasons:

  1. User-Friendly Interface: WordPress offers an intuitive interface, making it easy for beginners to start blogging without needing extensive technical knowledge.
  2. Customisation Options: WordPress provides a wide range of themes and plugins, allowing users to customise their blogs to suit their preferences and needs.
  3. Scalability: WordPress is highly scalable, meaning it can accommodate growing blogs with ease as well as bloggers starting out.
  4. SEO-Friendly: WordPress is designed with search engine optimization (SEO) in mind. It offers various SEO plugins and features that help improve your blog’s visibility in search engine results, ultimately driving more traffic to your site.
  5. Regular Updates and Security: WordPress regularly releases updates to improve functionality, performance, and security. Users can easily update their WordPress installations with a single click, ensuring that their blogs remain secure and up-to-date.
  6. Integration with Third-Party Services: WordPress integrates seamlessly with various third-party services and tools, such as social media platforms, email marketing services, analytics tools, and more, enabling bloggers to extend the functionality of their sites as needed.

However by default WordPress offers a basic blog, a simple homepage that just shows the most recent posts in that order. But what if you wanted to create something a little more slick? Perhaps you are wondering how to setup an Ajax WordPress blog.

What is Ajax?

Ajax stands for Asynchronous JavaScript and XML. It’s a web development technique used to create interactive and dynamic web applications. Ajax allows web pages to send and receive data from a server asynchronously, meaning it can do so without reloading the entire page.

Imagine you want to create a search tool but instead of sending users to another page to get their results you want them to display underneath the search bar. When you send a search request on WordPress its sending the users search query to the WordPress servers and the server will send back the results it finds.

Ajax makes that process seamless and allows you to make that request within the same page without needing to refresh the page or change the page.

How can we use this to make a nice blog?

Using Ajax we can make a seamless blogging process for users, allowing for search, filtering and loading more blogs. Thorough this guide we will show you how to make seamless blog search bar that displays the results in real time on the page, show how to filter your blog posts by a number of categories and how to load more blogs without going to a page 2.

Is Ajax good for SEO?

There is a tradeoff for using an Ajax blog. If it’s done incorrectly it can be bad for SEO purposes, when you use a normal blog home page google will see you have x number of posts on that page, it will also see that you have 10 pages of posts as WordPress will create pages inside your blog, for example: /blog/page/2/.

Ajax will stop that process and puts all of the posts essentially onto one page, obviously you will still have your posts individual pages so its not all bad, you are just losing one page (your blog homepage) that will look blank to search engines.

Realistically it’s not going to make that much of a difference as a blog homepage doesn’t tend have alot of content on it anyway and it’s usually the blog post’s themselves that are indexed.

On the flip side, your blog is going to be a fantastic user experience and it’s going to load lightning fast for your users as theirs so little to load on the initial page load, lets get started with How to setup an Ajax WordPress Blog.

How to setup an Ajax WordPress Blog with a plugin

To setup an Ajax WordPress blog with a plugin theres a few options you can use, we will break the different elements up so you can pick and choose which features you want to add to your blog.

Ajax Load more

The first plugin you can use is the Ajax Load More this lets you create an Ajax load more button, this will allow you to embed a small ‘load more’ button at the bottom of your posts page. You can customise this to automatically trigger as users scroll down the page and it will load another set of posts.

Or you can have it so users how to click the button to load more, personally I prefer to click the button so a user action triggers the posts loading, this prevents the page from jumping unexpectedly.

You can head to this page to download the Ajax Load More plugin, from here you can download and install the plugin to your WordPress website, or install it directly from your WordPress plugin hub.

Install the plugin and make sure to activate it. Go to the settings page and there you can set a number of things, I’d recommend changing the container type to a div so you have control over the items, you can also set a container class if you wish. If you are a WordPress beginner keep the ‘Disable CSS’ checkbox unticked.

Feel free to play around with the settings until you get something you are happy with, and fits in with the theme of your website.

Once you are done head to the shortcode builder, here you can pick which type of posts you want to load, set up no results texts change your button text and colours & you can turn on auto load when you are scrolling.

Once you have setup your shortcode settings, scroll back to the top and add an ID for your shortcode or generate one, you can copy the shortcode from right hand side.

How to setup an ajax blog settings page

Create a new page or go to your blog homepage. In their you can add a Gutenberg shortcode block and paste in what we have just copied. Then you can publish the changes, if you head to the front end of the page you just build you will now have an Ajax WordPress blog!

Scroll to the bottom and click the button to see more posts being added without needing to change page! Obviously you will need to have enough blogs to warrant the button being there or it will be hidden. The default amount of blogs per page is 10, you can change that in your WordPress reading settings.

To create a search bar for your site or just your blog page, we will use the Ajax Search Lite plugin, this is a great, easy to use plugin that allows Ajax searching from the get go. You can get the Ajax Search Lite plugin from the WordPress plugin directory. Download and install the plugin and make sure to activate it!

The Ajax Search Lite plugin adds functionality to easily search through your website with an ajax search bar, this plugin is similar to the previous plugin where you can change things in the settings and then you just need to put a shortcode on your page.

Go through the settings and familiarise yourself with parts of it, in there you can look at which posts types you want to search through, if you want to just create Ajax search for your blog, just make sure only posts are added to it. If you have more than one post type in your blog, such as posts, guides and more you include these as well.

You can also change what the plugin searches through, such as the title of your posts, the content and categories for example, I think the default settings work really well.

Wordpress Ajax Search settings

Once you are doing tinkering copy the shortcode from the very top of the page and you can add it to the top of your blog page. It will be something along the lines of [wpdreams_ajaxsearchlite].

You will see a large search bar on your blog page which will now search through your blog posts and display them to the user! This is great for boosting user engagement rates and helping them find the post they are looking for.

You can tinker with the settings if you want to change colours, what the results show and the weightings of the results, keep playing with it until you think its right for you and your users.

This plugin also comes with autocomplete based on your websites content, which is a handy extra feature!

WordPress Ajax post filtering with a plugin

To add WordPress Ajax post filtering we recommend using the Categories Ajax filter plugin, you can download this from the WordPress plugin directory.

Download the plugin from the Categories Ajax filters plugin page, you can get this from the link. Make sure to install and activate the plugin.

Head to the new Category filter options page in your admin area. Here you can create a new filter, so click on Add new. In there you can set a name for your filter, for example ‘Category’, then look through the settings.

The main things you want to look at is on the first page, the type of psots you are filtering in our case this wants to be posts, and what we are filtering by. This is called a ‘Taxonomy’, which basically means a type of category. You will see this written at taxonomy so it’s not confused with the WordPress category page, but I like to remember it as just a type of category.

You can also pick if you want to exclude any terms from the taxonomy you have picked, I’d recommend excluding categories such as ‘uncategorised’ and things like that that don’t mean anything to users.

Once you are happy with your filters hit the publish button at the right side of the page.

Wordpress Ajax post filtering with a plugin settings

Now it’s published we can get the shortcode form the ‘Shortcode’ tab on the left side of the filter you just created. It will be something like [caf_filter id=’795′].

Take your shortcode like the other pages and add it to your WordPress blog home page. You will now have a fabulously decorated list at the top of your blog page with your categories listed out, and you can click these to filter your posts by category!

Ajax filters categories

How to setup an Ajax WordPress Blog with code

To setup an Ajax WordPress blog using code is quite a difficult thing to do. It requires a good amount of knowledge in HTML, CSS, PHP and Javascript/JQuery. It’s also a hard thing to debug if it goes wrong as Ajax will not give nice user friendly error messages.

Setting up a blog template

Create a new page template and call it blog, in there you want to import your header and footer, and add some basic styles to make sure your page looks good. If you are struggling with this part we recommend you use plugins instead.

Your blog template should look something like this:

Blog homepage

Make sure you have a class that is easily explainable as the blog page and is unique to your blog post page, in this case I’ve used blog. Then have somewhere for your results to go into, I’ve used a class called blog__results and make sure you have somewhere for your pagination to go.

I’ve also used a loader, this just shows the front end user something to let them know its working and loading the results. Without this I think it can look like the site is broken or not responding, especially if you are bringing back a large number of results.

If you want to preload posts here with a WP Query you can, but I feel it makes it a little more complicated going forward when you get into pagination.

Set up this page and get it nicely styled within your website’s theme using dummy data. Make sure to create a page on your site and select the blog template from the dropdown in the page attributes.

WordPress Ajax blog post Javascript

Now you have a blog home page but theres nothing on it! Time for some Javascript. Create your JS file, i’m going to use jQuery here as I feel its more user friendly for Ajax calls, and its baked into WordPress so it’s not slowing anything down by adding it in.

Setting up ajax blog post JS settings

Here is the settings I’ve used for my blog post, these are global to the JS and can be changed & accessed in any functions below it. My settings have defaults for search, filtering and pagination but just focus on the paged settings which is keeping track of what page we are on.

Then below we see we have the check to get posts. This is where your class that’s only on the blog home page comes in, this checks if we are on the blog homepage and will call the getPosts function which is our Ajax function to pull posts from the server.

In the function we want to pass through the settings that were set earlier, whenever you call getPosts send the settings so its always consistent. Your call should just be getPosts(s.paged).

We also want to handle the ability to load more blog posts on a button click, so remember your load more button class from the template and let’s add a click listener.

This checks for the click of the button and then it increases our paged setting at the top of the JS page, and then when we pass this through the Ajax function in the call to getPosts it knows we are wanting posts from the next page. If you were using pagination you could increase s.paged by however many pages you are going to.

Now let’s get into the actual getPosts function, this is the code that calls to the WordPress server and pulls back the posts we want to display to our users.

So when we call getPosts the first we want to do is display the loading icon to the user to let them know that their click has started something working and the page hasn’t just frozen. To do that we remove the hidden class that is hiding it.

Then we call the Ajax function within jQuery, if you aren’t using jQuery your Ajax function will be a lot bigger than this. The url part is telling the function where it can access the Ajax library this is built in WordPress. The type is the type of Ajax function we are running, do not be confused into thinking this is the type of results we want from Ajax, e.g. page/post etc. We are posting a request with parameters to our Ajax function.

Data is what we are posting with our Ajax request, here we are saying the action we want to call, in this instance we are calling a PHP function inside WordPress called get_blog. Paged is sending which page of results we want back, in the first instance it will be 0 for the first page of results, and if we have clicked load more it will be 1,2,3,4 etc. The datatype is what sort of data we will receive back, I’m going to ask HTML back and we can easily slot it into the page.

The success part is what we want to do once we have successfully received data back from the call. So we are going to append the new results onto the end of the current results wrapper, so it added another 9 blog posts. Once that’s done we can hide the loader as the request is finished and the user will know their action is complete.

The PHP part of how to setup an Ajax WordPress Blog

Now we have the template setup, we have the Javascript checking for the page and loading more posts, what we need now is the posts themselves! You want to add the Ajax function into your WordPress themes functions.php.

Here is the get_blog function in our WordPress theme, it looks complicated but let’s break it down:

Wordpress ajax theme get posts function

The add actions at the top are what the JS Ajax function is looking for, the wp_ajax_nopriv tells WordPress this is an Ajax function and its not private, i.e. accessible from other code. Then the get_blog part is what must match your Ajax action.

Then we can open the function like you would do in JS. We will be calling a WP Query to pull the posts we need, so the first part is setting the variables for that. We want to pull only posts, we want to pull back 4 posts per page, yours can be whatever you like.

We want to get posts from the page the user is currently on, if you remember back to the javascript this is the paged variable we sent through. You can pick up variables you send through really easily by just adding $_POST and then your variable name you called it in your data section of the Ajax call. And obviously we only wanted published posts.

Then we call the WP Query, check if it has posts and if so we can loop through them. This part of the function will need to match however you are laying out your blog home page results. This code will look like this if you had the CSS to match it.

Blog layout example

But, you can use the functions in the code to get the categories, dates, titles etc in your own code.

ajax wordpress loop

Here I am looping through the results, I get all of my variables that might need to be changed before we go to the html, as you can’t call functions that need to be tweaked inside the html. So here I am getting categories, in my case every post only has 1, you might have multiple so will need to handle that, then I set a base image incase it doesn’t have a featured image. Then we check if there is a featured image and if so overwrite $image.

Then we head to our html_str which what we will be returning to the JS. I recommend you write this out with line breaks so you get it right and then you can use a minifier to make it smaller. All I’m doing here is writing out the html for the blog result and then the blue parts are adding the content directly from the post itself.

Once that’s done we look to the end of the PHP Ajax function:

sending the results back to the Js from AJAX

I choose to add the html string to an array, the array also contains the maximum number of pages we can get from my blog posts from the variables I set at the start. For example, my blog has 20 posts, my posts per page is 5 so the max_pages is 4. This can be useful to use in your JS to hide your load more button if the max number of posts have been displayed.

So we then echo the $return_obj, which is essentially acting as a return here and that will send it back to the javascript.

Looking back to our Javascript we are now in the Success part of the Ajax function, and we append the response to the bottom of the results. Feel free to console.log the response and see how it is encoded in JSON, and how max_pages comes back with it.

If you go to your blog home page on your WordPress site, you should now see your posts loading! If you get nothing check your console for a 500 error, this is about as helpful as Ajax gets with errors. But I recommend double checking your html_str you are sending as it may contain a spelling mistake in the functions.

If that fails just start commenting out parts until you narrow it down to the culprit you can return anything from your PHP function to help with debugging from the wp_query itself to just text to see if it works!

Please note is really complex stuff that you are building here so if you don’t get it straight away don’t be put off and just reread through this post. Once you are happy with it, you can start looking to add filters, search and more. Hint – It’s just a case of adding more settings to your JS and calling getPosts when the user changes a select box or finishes typing in a search box.