How to sort pre_get_posts by a meta field whose value is a number from largest to smallest

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:

  1. meta_key — this is the meta key you want to sort by.
  2. orderby — specifies that the sorting should be done by the numeric value of the meta field (meta_value_num).
  3. 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).

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

Why Files with Identical Content (*.js, *.php, *.css) Can Have Different Sizes?

When developers compare files with identical content but notice that their sizes differ, it can be perplexing. Let’s explore why this happens and what factors influence the size of files with extensions like *.js, *.php, and *.css. 1. File Encoding One of the key factors affecting file size is text encoding. The most common encodings…
Read more

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more