I’m developing a custom WordPress theme and I’m encountering issues while trying to implement custom paging and sorting using WP_Query. The goal is to allow users to sort posts by custom meta fields and paginate through the sorted results.
Here’s the detailed setup:
Custom Meta Fields:
_yuvi_art_date (String, various formats like “16th century (1500 – 1600)”, “19th century (1819)”, “1st half of the 16th century (1500 – 1550)”, “1900”, etc.)
Sorting Options:
By post_date
By custom meta field _yuvi_art_date
By custom meta field average_rating
Pagination:
Display 12 posts per page.
Maintain sorting across pages.
Current Code:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$orderby = isset($_GET['orderby']) ? $_GET['orderby'] : 'post_date';
$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
$args = array(
'post_type' => 'post',
'posts_per_page' => 12,
'paged' => $paged,
'orderby' => $orderby,
'order' => $order,
'meta_query' => array()
);
if ($orderby == '_yuvi_art_date') {
$args['orderby'] = 'meta_value';
$args['meta_key'] = '_yuvi_art_date';
}
$query = new WP_Query($args);
Issues:
Sorting by _yuvi_art_date: Given the format variations in _yuvi_art_date, sorting doesn’t work as expected. How can I normalize these values or sort them correctly considering the format variations?
Maintaining Sorting Across Pages: The sorting seems to reset on pagination. How can I ensure that the selected sorting order persists across different pages?
Performance Concerns: With a large number of posts, is this approach efficient? If not, what are the best practices for implementing this kind of sorting and paging?
Custom Sorting Options: How can I implement custom sorting logic, such as sorting by specific ranges of _yuvi_art_date (e.g., “1500s”, “1600s”, etc.)?
Additional Context:
I’ve considered converting _yuvi_art_date to a standardized format before querying, but I’m unsure of the best approach to do this in WordPress.
The theme supports AJAX for loading more posts, so the solution should be compatible with AJAX-based loading.
Any guidance or suggestions on how to tackle these issues would be greatly appreciated!
Example Data:
Some examples of the _yuvi_art_date meta values:
“16th century (1500 – 1600)”
“19th century (1819)”
“1st half of the 16th century (1500 – 1550)”
“1900”
Thanks in advance!
What I’ve Tried:
Using pre_get_posts to modify the query.
Creating custom SQL queries, but this bypasses some WordPress functionalities which I want to avoid.