How to Create a WordPress Alternative URL to Archive Page using WP_Query and AJAX
As a WordPress developer, you often encounter the need to create custom post types and archive pages to display those posts in a unique way. However, the default WordPress archive functionality may not always meet your specific requirements. In this article, we'll explore how to create a WordPress alternative URL to an archive page using the WP_Query
class and AJAX to provide a more dynamic and customizable solution.
Understand the Problem
WordPress by default provides an archive page for each post type, accessible through a URL like example.com/post-type/
. While this works well in many cases, there may be scenarios where you need more control over the archive page's layout, functionality, and URL structure.
For example, let's say you have a custom post type called "Albums" and you want to display the album covers in a grid layout on a dedicated page, with the ability to filter the albums based on various criteria using AJAX. The default WordPress archive page for the "Albums" post type might not be sufficient to meet these requirements.
Create a Custom Archive Page Template
To create a WordPress alternative URL to an archive page, we'll start by creating a custom page template. This template will be used to display the custom post type archive.
-
In your WordPress theme's directory, create a new file called page-albums.php
. This file will serve as the template for your custom album archive page.
-
In the page-albums.php
file, add the following code:
<?php
/*
Template Name: Albums Archive
*/
get_header();
?>
<div class="container">
<h1>Our Albums</h1>
<div id="album-grid">
<?php
// The Query
$the_query = new WP_Query(array(
'post_type' => 'albums',
'posts_per_page' => -1,
));
// The Loop
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
$the_query->the_post();
?>
<div class="album-item">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('thumbnail'); ?>
<h3><?php the_title(); ?></h3>
</a>
</div>
<?php
}
} else {
// no posts found
}
wp_reset_postdata();
?>
</div>
</div>
<?php
get_footer();
?>
In this template, we're using the WP_Query
class to retrieve all the posts of the "Albums" custom post type and displaying them in a grid layout. The the_post_thumbnail
function is used to display the album cover image, and the the_title
function is used to display the album title.
-
Create a new WordPress page and select the "Albums Archive" template from the Page Attributes section in the WordPress editor. This will assign the custom template to the page.
-
Publish the page, and you should now be able to access the custom album archive page at a URL like example.com/albums
.
Implement AJAX Filtering
To add AJAX filtering to the album archive page, we'll need to create some JavaScript code to handle the filtering functionality.
- Enqueue the necessary JavaScript and CSS files in your
functions.php
file:
function my_theme_scripts() {
wp_enqueue_script('my-ajax-script', get_template_directory_uri() . '/js/ajax-filter.js', array('jquery'), '1.0.0', true);
wp_localize_script('my-ajax-script', 'ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
add_action('wp_enqueue_scripts', 'my_theme_scripts');
- Create a new file called
ajax-filter.js
in your theme's /js/
directory and add the following code:
jQuery(document).ready(function($) {
// Add event listener to the filter buttons
$('.filter-btn').on('click', function() {
var filterValue = $(this).data('filter');
filterAlbums(filterValue);
});
function filterAlbums(filterValue) {
$.ajax({
url: ajax_object.ajax_url,
type: 'POST',
data: {
action: 'filter_albums',
filter: filterValue
},
beforeSend: function() {
// Show a loading indicator
$('#album-grid').html('<div class="loading">Loading...</div>');
},
success: function(response) {
// Update the album grid with the filtered results
$('#album-grid').html(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
}
});
- In your
page-albums.php
file, add the following code to create the filter buttons:
<div class="filters">
<button class="filter-btn" data-filter="all">All</button>
<button class="filter-btn" data-filter="rock">Rock</button>
<button class="filter-btn" data-filter="pop">Pop</button>
<button class="filter-btn" data-filter="classical">Classical</button>
</div>
- Finally, create a new function in your
functions.php
file to handle the AJAX request and return the filtered album grid:
function filter_albums() {
$filter = sanitize_text_field($_POST['filter']);
$args = array(
'post_type' => 'albums',
'posts_per_page' => -1,
);
if ($filter != 'all') {
$args['tax_query'] = array(
array(
'taxonomy' => 'album_genre',
'field' => 'slug',
'terms' => $filter,
),
);
}
$the_query = new WP_Query($args);
if ($the_query->have_posts()) {
ob_start();
while ($the_query->have_posts()) {
$the_query->the_post();
?>
<div class="album-item">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('thumbnail'); ?>
<h3><?php the_title(); ?></h3>
</a>
</div>
<?php
}
wp_reset_postdata();
$output = ob_get_clean();
echo $output;
} else {
echo '<div class="no-results">No albums found.</div>';
}
wp_die();
}
add_action('wp_ajax_filter_albums', 'filter_albums');
add_action('wp_ajax_nopriv_filter_albums', 'filter_albums');
In this code, we're using the WP_Query
class to retrieve the albums based on the selected filter. The filter_albums
function is called via AJAX, and it returns the updated album grid HTML to be displayed on the page.
With these changes, you should now have a custom WordPress archive page for your "Albums" custom post type, with the ability to filter the albums using AJAX.
Conclusion
By creating a custom page template and using WP_Query
to retrieve the custom posts, you can easily create a WordPress alternative URL to an archive page. Additionally, by implementing AJAX filtering, you can provide a more dynamic and responsive user experience for your users.
This approach can be applied to various custom post types and archive pages, allowing you to tailor the display and functionality to your specific requirements. Remember to optimize the code for performance, security, and maintainability, and you'll have a powerful and flexible solution for your WordPress-powered website.
If you're interested in further optimizing your website's conversion rates and user experience, be sure to check out Flowpoint.ai. Flowpoint can help you identify technical issues, UX problems, and content opportunities that are impacting your website's performance, and it can generate AI-powered recommendations to help you address them
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.