To sort by a meta field (meta key) in WordPress using the pre_get_posts
hook, where the value is a number and should be ordered from highest to lowest, you can add custom code to your theme’s functions file (e.g., functions.php
). Here’s an example:
add_action('pre_get_posts', 'custom_order_by_meta_value');
function custom_order_by_meta_value($query) {
// Check if this is the main query and not in the admin panel
if (!is_admin() && $query->is_main_query()) {
// Check for the desired post type (e.g., 'post')
if ($query->is_post_type_archive('your_post_type')) {
// Specify the meta key for sorting
$meta_key = 'your_meta_key';
// Set the query to order by the numeric meta value in descending order
$query->set('meta_key', $meta_key);
$query->set('orderby', 'meta_value_num');
$query->set('order', 'DESC');
}
}
}
Explanation:
meta_key
— this is the meta key you want to sort by.orderby
— specifies that the sorting should be done by the numeric value of the meta field (meta_value_num
).order
— specifies that the sorting should be in descending order (DESC
).
If you’re using a different post type or need additional query conditions (e.g., category, tag), you can adjust the conditions inside the function to suit your needs.
This code will work for the main query on the archive page of the specified post type (your_post_type
).