Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Order by meta value pro first then meta value free in my search function

EDIT 2 – FINAL EDIT

Just before I start with this edit, just a few things here

  • The code in my answer are the basics and meant to demonstrate the concepts. I have now tested both sets of code, and all works as expected. You have to add all your desired mark-up, styling and template tags yourself.

  • On the part of implementation, this is entirely up to you, we are not here to implement code for you. It is expected that you do at least have some knowledge on how to use and implement this code into your theme

You have confirmed that this is your search.php, which renders my code in my original answer useless. You should never change the main query with a custom one as this is always problematic as you have seen. Please see this post I have done on this subject

My solution for you would be is to paste the code from my first edit (EDIT 1) in your functions.php. You will have to modify the pre_get_posts action as needed. I have tested the code and it works perfectly. For this to work, you need to make use of the main loop in search.php.

ORIGINAL ANSWER

What I’ve read and understood from your question is that all pro values must be first ordered by date, and then free to follow ordered randomly

We are going to make use of basically the same idea as in your previous question with a few modifications

Just one note before I start, you should not make use of custom SQL queries. Make use of pre_get_posts, WP_Query or get_posts rather to create/adjust/modify your queries accordingly

I’m still a SQL learner, so I’m going to scrap your idea and work with WP_Query

The type of sorting that you want is not possible with the above mentioned native functions. Also, you don’t need to run two queries to achieve this, one is enough.

My idea here would be to retrieve all posts within the meta_value of pro and free. We will keep the default ‘orderby’ and ‘order’ parameters as this does not matter. We will use PHP to achieve the desired sort orders

So, lets code:

STEP 1

As previously stated, we need get all the posts which have a meta_value of pro and value

$args = [
    'post_type'         => 'listing',
    'meta_key'          => 'geocraft_listing_type',
    'meta_value'        => 'free, pro',
    'meta_compare'      => 'IN',
    'posts_per_page'    => -1,
];

$the_query = new WP_Query( $args );

STEP 2

In my personal opinion, the best way to achieve your sort order is to break the $posts array into two separate arrays, one array will hold all posts with a meta_value of pro while the other array will hold posts with meta_value free.

$free = [];
$pro = [];
foreach ( $the_query->posts as $post ) {
    $meta = get_post_meta( $post->ID, 'geocraft_listing_type', true );
    if ( 'free' == $meta ) {
        $free[] = $post;  
    }else{
        $pro[] = $post;  
    }
}
unset($post);

STEP 3

The array which holds the posts with meta_value pro will be left untouched, this array of posts will already be sorted according to post date. We need to sort the array which holds the posts with meta_value free

As you need this posts to be sorted randomly, we are going to make use of the PHP function shuffle() to shuffle these posts so that they are going to be displayed randomly

shuffle($free);

STEP 4

We need to unset the original $posts and reset it with a new value. This value will be created by merging our two arrays together, pro first, then free. To achieve this, make use of array_merge(). This new array will be set as the new value of $posts

unset($the_query->posts);
$the_query->posts = array_merge($pro, $free);

STEP 5

You can now loop through your posts as normal

if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();

        echo '<li>' . get_post_meta( $post->ID, 'geocraft_listing_type', true ). '</br>' . get_the_title() . '</li>';

    }
    echo '</ul>';
} 
wp_reset_postdata();

ALL TOGETHER NOW

<?php
$args = [
    'post_type'         => 'listing',
    'meta_key'          => 'geocraft_listing_type',
    'meta_value'        => 'free, pro',
    'meta_compare'      => 'IN',
    'posts_per_page'    => -1,
];

$the_query = new WP_Query( $args );

$free = [];
$pro = [];
foreach ( $the_query->posts as $post ) {
    $meta = get_post_meta( $post->ID, 'geocraft_listing_type', true );
    if ( 'free' == $meta ) {
        $free[] = $post;  
    }else{
        $pro[] = $post;  
    }
}
unset($post);
shuffle($free);
unset($the_query->posts);
$the_query->posts = array_merge($pro, $free);

if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();

        echo '<li>' . get_post_meta( $post->ID, 'geocraft_listing_type', true ). '</br>' . get_the_title() . '</li>';

    }
    echo '</ul>';
} 
wp_reset_postdata();

You can modify this code to use pre_get_posts and the_posts filter if this is suppose to be the main query.

EDIT 1

If this was suppose to be done on the search page as the main query, you would use pre_get_posts to alter the main query on the search page. I’m not going to explain everything in detail as it should work in the same way as above with WP_Query

In your functions.php, add the following code. This will change the main query only for the search page

add_action( 'pre_get_posts', function ( $query ) {
    if ( !is_admin() && $query->is_search() && $query->is_main_query() ) {
        $query->set( 'post_type', 'listings' );
        $query->set( 'meta_key', 'geocraft_listing_type' );
        $query->set( 'meta_value', 'free, pro' );
        $query->set( 'meta_compare', 'IN' );
        $query->set( 'posts_per_page', '-1' );
    }
});

You are now going to use the_posts filter to filter the sorting order on the search page.

So, again in your functions.php, add the following code

add_filter( 'the_posts', function ($posts, $query) {
  if( $query->is_main_query() && $query->is_search() ) {
    $free = [];
    $pro = [];
    foreach ( $posts as $post ) {
        $meta = get_post_meta( $post->ID, 'geocraft_listing_type', true );
        if ( 'free' == $meta ) {
            $free[] = $post;  
        }else{
            $pro[] = $post;  
        }
    }
    unset($post);
    shuffle($free);
    $posts = array_merge($pro, $free);
    }
    return $posts;  
}, 
10, 2 );

Inside your search.php you don’t need to modify anything. All you need in there is the default loop.

Related Posts:

  1. How to display liked posts of current user in wordpress?
  2. Query metas (and not : query posts by metas)
  3. Query posts according to specific post meta values
  4. get_post_meta with WP_query
  5. Is there any way to get all custom posts and all custom terms with it’s meta in few queries?
  6. What is the best way to query posts based on live data?
  7. How can I create a meta_query with an array as meta_field?
  8. How can I query all users who registered today?
  9. Search custom post type by meta data
  10. Custom Queries: Joining On Meta Values From Two Custom Post Types
  11. WordPress creating excessive joins on meta_query with search
  12. Filter query posts by the count of metas for a meta key
  13. Save default value for empty or missing post meta
  14. Grouping related postmeta data via SQL query
  15. How can I apply a meta query for a single custom post type in the main query?
  16. How do I find if a page has a template?
  17. mySQL query. ORDER BY meta_key
  18. Remove posts from query for events whose start date has passed
  19. How to check current user in meta value array in WP_Query meta_query
  20. WP_POSTMETA – What do these values mean inside the data structure?
  21. How to orderby multiple meta fields if some fields are empty
  22. How to orderby multiple meta fields with another meta query
  23. Issue with using add_rewrite_rule() for post querying custom fields
  24. Meta Query relation “AND” then set array accordingly
  25. Query returning same results even though the ID changes
  26. get_users with array as meta_value
  27. Declaring a var, placing it in a query and using the output of the query?
  28. WordPress Mysql query and Duplicate
  29. WP_Query meta compare must include ALL array values
  30. Combining two meta_values within one row with query
  31. Excluding posts by meta, and also keeping posts without the meta
  32. How to “orderby” the first array in a meta_query that uses multiply keys?
  33. I can not display meta value in extras.php and template-tags.php
  34. Negative meta_query if storing multiple post_meta values with shared meta_key
  35. meta_query not working
  36. WordPress query: merge meta key (number) values and sort
  37. Query against multiple locations within single custom post type post
  38. Restrict WordPress search to a single ACF field
  39. Sort by postmeta on when searching
  40. Multiple meta key and value search in the query
  41. Fastest and most efficient SQL query to check if UID exists
  42. Use $wpdb->get_results with filter based on array
  43. Query Posts that have or don’t have a meta_value and order by the same ASC
  44. meta query always fails even if data is correct
  45. Custom MySQL Query for Post and Post Meta
  46. list or get meta_key where meta_value is ‘something’
  47. WP_Query orderby meta key/value suddely stopped working
  48. Check for custom field value in different post type than current one and do something
  49. WP Query Args – search by meta_key or title
  50. Meta Query compare with LIKE pulls similar post types: 55 and 155, and 1,155
  51. simple sql query on wp_postmeta very slow
  52. How to Use Wildcards in $wpdb Queries Using $wpdb->get_results & $wpdb->prepare?
  53. Compare two numeric custom fields
  54. Custom query filter not working on woocommerce category page
  55. How to delete a transient on post/page publish?
  56. Multiple Values stored as array in Meta Query
  57. How to extract all ID variables from a query string?
  58. How to remove duplicate query on page load or make them cacheable
  59. Pull post meta with post_query?
  60. Huge amount of queries on my site
  61. WordPress Orderby Numeric Value Not Working
  62. Searching by meta values showing inappropriate result
  63. How do I use get_query_var() within plguin code
  64. How to display related posts by same publish date?
  65. Get post according to current taxonomy
  66. Performance when getting post meta for post retrieved by meta value
  67. Ordering by a metadata subfield in WordPress?
  68. Alter query with posts_clauses to retrieve NULL values last
  69. How to create a meta_query to get all posts with a specific meta data?
  70. WordPress Query orderby title with UTF8 string in title
  71. Searching With Apostrophe
  72. Saving zero as meta value
  73. get_posts showing only 5 posts. (nopaging and posts_per_page -1 not working)
  74. how to insert missing tags into the posts through mySQL?
  75. How to write update query in WordPress to expire transients
  76. Query Nickname rather than Display Name in custom Woocommerce plugin
  77. Nested array issue in meta_query
  78. Get previous posts list
  79. how to replace old DW site with new WP site? [closed]
  80. WP_Meta_Query object with conditionals
  81. WordPress SQL query to tag all posts containing a specific word on title
  82. Order terms by count – missing terms
  83. Why doesn’t my WP Meta Query return any results?
  84. updating one custom meta field only
  85. Formatting a date/time returned from a custom $wpdb query
  86. Displaying data from custom table
  87. SEO friendly query vars
  88. Show posts from WP Custom Post Type selected from a field in a metabox
  89. Query by meta value (add a dropdown of all values)
  90. Add Hook for clearing transient when post is added
  91. How to fetch meta_value and meta_key in matrix after ajax request by post_id
  92. Show links to child pages on both parent AND child pages
  93. Modify Global Posts Plugin
  94. How to reference same column name but different table in custom db query
  95. Retrieving custom field array value through db query
  96. How do I troubleshoot Maximum execution time of 60 seconds exceeded in updating a Media File?
  97. update $wpdb one query
  98. How to use a dynamic term id for the query block
  99. Update post meta array – add new, single value
  100. getEntityRecords/useEntityRecords: How to use CPT metadata?
Categories query Tags meta-query, meta-value, post-meta, query
How to create a specific Web App with WordPress?
Date format – Meta Box plugin

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress