Ordering posts by a custom field in WordPress can significantly enhance your site’s functionality, especially when you're dealing with complex content structures. Whether you're running a blog, an e-commerce site, or a portfolio, custom post ordering allows you to showcase your content in a way that better meets your visitors' needs. You can use the following code to sort posts by a custom field using the "pre_get_posts" hook:
function themesdna_order_posts_by_custom_field($query) {
if (!is_admin() && $query->is_main_query()) {
if ($query->is_home() || $query->is_search() || $query->is_archive()) { // Adjust conditions based on where you want this to apply
$query->set('meta_key', 'your_custom_field_key'); // Replace with your custom field key
$query->set('orderby', 'meta_value'); // Or 'meta_value_num' for numerical values
$query->set('order', 'ASC'); // or 'DESC'
}
}
}
add_action('pre_get_posts', 'themesdna_order_posts_by_custom_field');
Note:
meta_key : Replace 'your_custom_field_key' with the actual key of the custom field you want to order by.
orderby : If your custom field contains text, use 'meta_value'. If it contains numbers (e.g., prices or ratings), use 'meta_value_num' to ensure proper numerical sorting.
order : Set this to 'ASC' for ascending order (lowest to highest) or 'DESC' for descending order (highest to lowest).
Example:
Suppose you have a custom field (meta key) called "event_date", and you want to order posts by that field. You can do this by adding the following code to your theme's functions.php file:
function themesdna_order_posts_by_custom_field($query) {
if (!is_admin() && $query->is_main_query()) {
if ($query->is_home() || $query->is_search() || $query->is_archive()) {
$query->set('meta_key', 'event_date');
$query->set('orderby', 'meta_value');
$query->set('order', 'ASC');
}
}
}
add_action('pre_get_posts', 'themesdna_order_posts_by_custom_field');