Blogercise

  • Home
  • Beginners
    • 1: Topic
    • 2: Name
    • 3: Setup
    • 4: CMS
    • 5: Design
    • 6: Post
    • 7: Promote
    • 8: SEO
    • 9: Money
    • 10: Grow
  • WordPress
    • bbPress
    • Genesis
  • My Plugins
    • bbpress Adsense
  • About
    • Hobby Blogger
    • Cookie Policy
    • Disclaimer

Genesis: AJAX Powered Front Page

Last Updated Jan 27th, 2015 (First published Jan 27th, 2015)Filed Under: Genesis, Wordpress 4 Comments

In this post I talk through how I got WordPress posts to dynamically appear on my site’s front page by allowing visitors to selecting tags and categories.

blg-demo-1

Not sure what I mean, here’s a demo.

Read on for the full story.

The Requirement

I recently had a requirement to dynamically update a site’s front page based on selection criteria chosen by the user.  If you are familiar with shopping sites that allow you to filter on product attributes without the page reloading then you will know what I mean.

For example, a user presses on the “wood” filter and all the wooden products magically appear, everything else fades out of the page.

I wanted to achieve this using WordPress and the Genesis framework. I was unable to find a good tutorial on this, yet I found a number of people who were also wondering how to implement this functionality. I therefore thought it was worth taking the time to share my results on Blogercise.com.

In this post I take you through a demo site I put together to illustrate how to make a dynamic AJAX powered front end for a WordPress Genesis framework site.

Tutorial and Demo Site

There’s plenty of information out there on the net, and I was able to eventually find all the pieces of the puzzle, however the purpose of this post is to bring the whole story together in one place and point towards the principles you need to understand to get his up and running.

I’ll take you through the background and then we’ll put together some code for you to have a go with.

This post takes you through the solution that I came up with, you can see the results on my demo site: Presents UK.

The site was put together to demo this tutorial.

Genesis Grid

By default a Genesis theme will list out blog posts on your front page. In my case I wanted to see a grid, specifically a 3×3 grid to show up 9 posts.

There are plenty of articles on manipulating the inbuilt Genesis Grid but I found things started getting complicated. A far easier solution was provided by Bill Erickson.

I would like to take this opportunity to thank him for his generosity in sharing his experiences on working with Genesis.  This article, and responses to queries in the comments were invaluable in getting my project completed.

If you wish to reproduce the output of my demo site, then the first step is to follow his guide and set up your own custom loop, we’ll go through an example in the next section.  It is this loop that we are going to manipulate using jQuery’s AJAX functionality.

In summary, you’ll be using the Genesis column classes to change the layout into two or more columns. The great thing about this is it becomes very easy to change the number of columns, check out the available classes here.

Customising Posts

As well as changing the layout of the front page, I also wanted to change how the post itself was going to look. In the case of the demo site each post is actually a product and I wanted to wrap them up in a box, give it some colour and also show a price.

By default, WordPress loops through and displays blog posts during “The Loop“. So if you ever need to change how posts are being displayed this is normally the first thing to look at.

Typically a plugin will affect this by manipulating the $wp_Query object, but Genesis actually has it’s own loop, think of it as a kind of wrapper to the main loop. As I wanted to completely change how posts were to be displayed I needed to replace this. However it would be equally valid to manipulate the genesis loop if this is adequate for your needs. This will work fine if you are looking for the AJAX effect but don’t wish to customise the posts.

But in my case the plugin needs to remove the standard loop and replace it with my own custom one:

        remove_action( 'genesis_loop', 'genesis_do_loop' );
        add_action( 'genesis_loop', 'my_custom_loop' );

We now need to add our custom function to call the loop and output the post.

In the example below I simply output the title and excerpt but you can shape this in anyway you like. In the more customised examoples I have done I have also called upon post meta data and custom taxonomy. The $post_id is available to you as you loop so it should be straightforward to access this information, the WordPress documentation will give you more information.

function my_custom_loop(){
 global $wp_query, $post;
 while( $wp_query->have_posts() ): $wp_query->the_post();
  $post_id      = get_the_id();
  $classes      = ' one-third';
  if( 0 == $wp_query->current_post || 0 == $wp_query->current_post % 3 )
   {$classes .= ' first';}
  echo '<div id="product-' . $wp_query->current_post . '" class="' . $classes . '">';
   echo "<a href='".get_permalink()."'>".get_the_title()."</a>";
   the_excerpt();
  echo "</div>";
endwhile;
}

The result is a front page that displays my desired grid, we now need to set this up to respond to user selected filters.

Push Button Filters

Next, I wanted to have some “buttons” at the top of my page that would allow users to make their selections. Although they don’t look like it, these are actually just check boxes in a regular html form. A little bit of CSS styling makes them appear more button like.

The buttons are output onto the page by hooking into Genesis and writing a simple function to output the form, there are plenty of tutorials on this topic if you are unfamiliar with how to achieve this.

When a user presses on the button, they are actually just checking the checkbox of the form. The state of these checkboxes is then posted back just like any other form. The difference is in how we trigger that post back to be made. Rather than needing the user to press “Enter” we’ll instead use AJAX technology to detect the user’s action on the fly and immediately post the results of the form back to the Genesis loop so that it can be updated.

The buttons in my form are built from terms created in custom WordPress taxonomies but you could easily use the standard in built ones (categories or tags). A user will check and uncheck the boxes and the AJAX code will post the results back so that we can filter our WordPress query based on the taxonomy terms that the user selected. For more information on advanced taxonomy queries, see this post.

AJAX with jQuery

With little experience of Javascript, this was the most intimidating part of the problem. Fortunately the jQuery library makes this as easy as it could possible be for hobby developers such as myself.

Thanks to the jQuery library you don’t need to understand the ins and outs of how to implement AJAX requests, you can simply take advantage of the code library to do all the heavy lifting and let it worry about browser compatibility etc. jQuery is already used by WordPress itself so you don’t need to worry about downloading or distributing it.

How does this work?

Here’s a quick summary of how we will use jQuery to dynamically update our page:

  • User interacts with the homepage, this is referred to an “Action”.
  • The action is picked up by jQuery and fires the AJAX request.
  • The request posts data to a PHP script.
  • The PHP script generates HTML to display on the screen.  This output replaces existing HTML already displayed.

So what we are doing is looking for the user selecting on of our filters on the page, when they do we are going to capture their input and run a new WordPress query to get the relevant posts and then get genesis to display this with a custom loop.

The jQuery Code

First, we need to be on the lookout for user input. The following code piece will fire a function called submitdata() when an action is detected in the class #filterform.

/*We are monitoring for a change event anywhere in our two forms*/
jQuery('#filterform').change( function(){
        submitdata();
        return false;
})

Next, once the action is detected, our submitdata() function is called. We are using the jQuery to make this process much easier. You can read more about their ajax method here.

Let’s step through:

  • We locate the form on our page using the class identifier #filterform
  • The current state of the form is loaded into a variable, we serialise the data so that it can be posted
  • A request is generated, here we specify where we are going to post the data
  • We specify what happens upon success.  In this case we load the output of our handler into our page.  This is essentially just some HTML code that will replace the existing  #productgrid div on that page.
  • Finally, there is some error handling

    window.submitdata = function (){

        // abort any pending request
            if (request) {
                console.log("msg: aborted");
                request.abort();
            }

         var serializedData = jQuery("#filterform").serialize();

             request = jQuery.ajax({
                type: 'POST',
                url: "/wp-content/plugins/wp-myplugin/handler.php",
                data: serializedData
            });

            // callback handler that will be called on success
            request.done(function (response, textStatus, jqXHR){
                // log a message to the console
                jQuery("#productgrid").html(response);
                console.log("msg: it worked!");
            });

            // callback handler that will be called on failure
            request.fail(function (jqXHR, textStatus, errorThrown){
                // log the error to the console
                console.error(
                    "msg: The following error occured: "+
                        textStatus, errorThrown
                );
            });

            // callback handler that will be called regardless
            // if the request failed or succeeded
            request.always(function () {
            });
        }

All being well, this js script will detect user input in the form and post back the results to our handler script (handler.php).

Applying the Filters

So, jQuery has captured a user action and sent us data back to our URL, how do we see the results of this on our page?

We are going to re-run the WordPress selection query in our handler script but this time we are going to feed in the results posted in from the form. This will tell WordPress to only return posts that belong to the taxonomy terms selected. The output is then passed back and displayed on our page, in this case the HTML generated, that contains our filtered posts, is displayed in the #productgrid div.

Here’s a cut down version to get you started. Let’s talk through it:

  • We don’t want this to be a full on WP page, this only needs to output the posts.  Our existing page already has everything else and this won’t change.
  • Grab the posted form, this will be serialised from the AJAX script so will need to be converted into a form suitable to be passed into the query arguments.
  • Setup the query arguments, this tells WordPress how to select the posts.  I want 9 published products that match my selected taxonomy terms.
  • We then run the query and loop through the results, as we loop through you can output the post.
<?php
// Our include
define('WP_USE_THEMES', false);
require_once('../../../../wp-load.php');

if (isset($_POST['tax']))       {$tax_query       = $_POST['tax'];}      else{$tax_query='';}
$tax_query = $this->convertPostToTaxQuery($tax_query);

//do loop


            $args = array(
                'posts_per_page' => 9,
                'post_type'      => 'product',
                'post_status'    => 'publish',
                'paged'          => get_query_var( 'paged' ),
                'tax_query'      => $tax_query
            );

global $wp_query;
$wp_query = new WP_Query( $args );

if( $wp_query->have_posts() )
        {
            // Output your post here

}else
   {echo "Please try another search!";}
   wp_reset_query();

exit;

This handler produces a chunk of html that then gets brought into the existing page, replacing the previous posts that were displayed. This has the effect of applying the filters the user has selected.

Final Thoughts

My example uses a grid, but the same idea could just as well be applied to a more standard layout, in fact there is no absolute requirement to have Genesis to build a site like this, but you will find it easier.

I do not consider myself an expert in jQuery so I’m afraid my example is fairly basic and may not work in all scenarios. I’d be interested in knowing how to make the posting URL dynamic for example.

Click here to see my demo. If you are a hobby WordPress blogger who likes to tinker with code then you will want to subscribe to our feed, add our RSS feed to your preferred reader, or enter your email into the subscription box at the bottom of this page.

Filed Under: Genesis, Wordpress Tagged With: AJAX, Genesis, jQuery, WordPress

About

Blogercise.com the site dedicated to hobby bloggers. If you are an amateur website builder looking to create revenue generating professional quality websites then this site is for you. Find Out More

Google+TwitterRSSWordPress

Get updates via Email

Enter your address to receive occasional emails helping you to become a better hobby blogger:

Recent Posts

  • Renaming A Domain
  • vBulletin to bbPress Migration Missing Topics
  • Vidahost Adds Let’s Encrypt SSL Support
  • WordPress Twitter Plugin: TweetWheel Review
  • How to add Geolocation to a WordPress Plugin

Navigation

  • Advanced
  • Affiliate Marketing
    • SkimLinks
    • SubmitEdge
  • Beginners Guide
    • Start Here
  • e107
  • Internet
  • Mediawiki
  • News
  • PHP
  • Search Engines
    • Search Engine Optimisation
  • Tech
  • Uncategorized
  • vbulletin
  • Wordpress
    • bbPress
    • Genesis
    • Plugins
      • Simple Affiliate Links
      • Simple Amazon Units
      • WPTurbo
    • Thesis

Follow me on Twitter

My Tweets

Our Sites

Pure Pixel - Nexus owner community.
SammyMobile.comSamsung owner community.
Presents UK - Gift ideas.
Redirect Links - Personal link shortener.

Top Posts & Pages

  • Renaming A Domain

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Copyright © 2019 · Metro Pro Theme on Genesis Framework · WordPress · Log in

This site uses cookies: Find out more.