How To Filter WordPress Posts Grid With MixItUp JQuery Library

Introduction

MixItUp is a high-performance, dependency-free jQuery library for animated DOM manipulation. It gives you the power to filter, sort, add and remove DOM elements with beautiful animations. In this tutorial, I’ll be showing us how to filter WordPress posts grid with MixItUp.

How MixItUp works

MixItUp provides DOM manipulation functions that can be used for filtering and sorting HTML elements that are already rendered on a page.

When dealing with a dataset of more than 1000 items, MixItUp Dataset API is a more efficient option to be considered instead of the DOM-based approach that I’ll be showing us.

Getting started

To see the library at work, we’ll be creating a simple WordPress plugin that displays a nice grid of our published posts with buttons for filtering them based on our filter conditions.

In your wp-content/plugins folder, create a new folder and name it mixitup-demo. Create a new file in the folder and name it mixitup-demo.php

Add the plugin header as shown below

/**
* Plugin Name: MixItUp Demo
* Description: Display WordPress posts in a nice grid and filter them
* with beautiful animations.
* Author: Shycoder
* Author URI: https://shycoder.com
* License: GPLv2 or later
*/

Loading MixItUp

Download the minified version of the library and put it in a new assets/js folder. We then include the library and jQuery in our project by enqueuing them like so

// enqueue scripts
add_action('wp_enqueue_scripts', 'md_enqueue_scripts');

function md_enqueue_scripts()
{
    // jQuery
    wp_register_script('jQuery', 'https://code.jquery.com/jquery-3.5.1.min.js', '', '', true);
    wp_enqueue_script('jQuery');

    // MixItUp
    wp_register_script('md-mixitup', plugin_dir_url(__FILE__) . 'assets/js/mixitup.min.js', array('jQuery'), '', true);
    wp_enqueue_script('md-mixitup');
}

Fetching WordPress posts

Next, we create another file and name it posts.php, include this file in our project.

require_once(plugin_dir_path(__FILE__) . '/posts.php');

This is where we’ll write the logic for displaying WordPress posts in a grid. We’ll use Bootstrap for handling the grid layout, and we’ll also write the logic for the filter buttons here.

Open the file and let’s add a simple function for fetching WordPress posts, and register a shortcode for displaying our posts grid later.

function md_get_posts()
{
    $args = array(
        'post_type' => 'post',
        'order' => 'DESC',
        'posts_per_page' => 6,
    );

    return new WP_Query($args);
}

// add shortcode for displaying posts grid
add_shortcode('md_posts', 'md_posts');

function md_posts() { }

The above function returns a WP_Query object of the first six posts in the database.

Adding the filter buttons

Next, let’s add filter buttons for displaying only the posts that are 1 month, two months, and a year old.

/**
 * Display filter buttons
 */
function md_filter_buttons()
{
?>
    <div class="controls">
        <button type="button" data-filter="all">All</button>
        <button type="button" data-filter=".one-month-old">1 Month Old</button>
        <button type="button" data-filter=".two-month-old">2 Month Old</button>
        <button type="button" data-filter=".one-year-old">1 year Old</button>
    </div>
<?php
}

We create our filter controls by adding data-filter attribute to the buttons. The value of this attribute should be the filter conditions. In our case, we want to fetch posts that are one month, two months, and a year old. So, our filter conditions are .one-month-old.two-month-old, .one-year-old. We’ll register these conditions with mixitup up later.

Writing the filter logic

Now let’s write the logic for checking if our filter conditions are true. This means we need a function for checking if a specific post is x days old. The function should return true if the condition is met, and false otherwise.

/**
 * Check if post was published x days ago
 * @param string $post_date $days 
 */
function md_is_days_old($post_date, $days)
{
    if (strtotime($post_date) < strtotime('-' . $days . 'days')) {
        return true;
    }

    return false;
}

The function above returns true if the post published date is less than x days and false if it’s not. We need this when checking how old a post is, as we plug the filter condition it belongs to.

Displaying the posts grid

To use bootstrap’s grid layout, add below to the md_enqueue_scripts in mixitup-demo.php file to include bootstrap in our project.

wp_register_style('md-bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
wp_enqueue_style('md-bootstrap');

In the posts.php file, add a new function for querying the post loop and displaying it with the grid.

function md_posts_grid()
{
    $posts = md_get_posts(); // display filter buttons md_filter_buttons(); 
?>
    <div cass="container">
        <div class="row">
            <?php while ($posts->have_posts()) {
                $posts->the_post(); ?>
                <div class="col-md-4 <?php echo $filter_arg; ?>">
                    <h3><?php echo the_title() ?></h3>
                    <small><?php echo the_excerpt() ?> </small>
                </div>
            <?php }
            wp_reset_postdata(); ?>
        </div>
    </div>
<?php }

The function above iterates through the posts loop and display the posts in a grid, with the filter buttons above the grid.

Next, we need to set up a mixitup container. Add mix to the class attribute of each post, and include the filter condition we created earlier as well.

function md_posts_grid()
{
    $posts = md_get_posts();
    $filter_arg = 'one-month-old'; // display filter buttons md_filter_buttons(); 
?>
    <div cass="container">
        <div class="row">
            <?php while ($posts->have_posts()) {
                $posts->the_post();
                if (md_is_days_old(get_the_date(), 60)) {
                    $filter_arg = 'two-month-old';
                }
                if (md_is_days_old(get_the_date(), 360)) {
                    $filter_arg = 'one-year-old';
                }
            ?>
                <div class="col-md-4 mix <?php echo $filter_arg; ?>">
                    <h3><?php echo the_title() ?></h3>
                    <small><?php echo the_excerpt() ?> </small>
                </div>
            <?php
            }

            wp_reset_postdata(); ?>
        </div>
    </div>
<?php }

We created a new variable $filter_args to store our filter conditions based on the value of our function md_is_days_old which checks if a post is x days old. Then, we display the value of the variable in the class attribute along with mix to register each post in the container.

Registering the MixItUp container

In our assets/js folder, create another file and name it script.js Add the below script to register mixitup container

var container = document.querySelector('.row');
var mixer = mixitup(container, {
    animation: {
        duration: 800,
        nudge: false,
        reverseOut: false,
        effects: 'fade scale(0.41)'
    }
});

Go to mixitup-demo.php file after this and enqueue the script inline like this

$script = file_get_contents(plugin_dir_url(__FILE__) . 'assets/js/script.js');
wp_add_inline_script('md-mixitup', $script, 'after');

Displaying the shortcode

Finally, let’s display the grid in the shortcode we created earlier.

function md_posts() {
    md_posts_grid();
}

Conclusion

Add a new page to WordPress and add the shortcode [md_posts].

After publishing the page, preview it and you should see a nice looking grid of your published posts, with buttons for filtering them. When you click on any of the buttons, the posts will be filtered based on the filter condition you clicked on.

See the demo below

The full plugin codes are available on Github
Check out the full MixItUp library tutorial here