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. SQL query based on two different custom field values
  52. How to display SQL query that ran in query?
  53. How to only display posts whose meta_value field is not empty?
  54. Query multiple meta key values?
  55. How to Optimize WP site for millions of posts
  56. order by numeric value for meta value
  57. Use REGEXP in WP_Query meta_query key
  58. How to get comments by post ID?
  59. Differences between wpdb->get_results() and wpdb->query()
  60. Is there a way of increasing the speed of this query?
  61. Get all image from single page using this query
  62. Get Terms by IDs with IDs order
  63. Reversing the order of posts AFTER the query is performed
  64. what are the numbers between curly brackets in search query
  65. simple sql query on wp_postmeta very slow
  66. Using WordPress public query variables
  67. SELECT max(meta_value) FROM wp_postmeta WHERE meta_key=’price’… stops working when value is over 999
  68. How to Use Wildcards in $wpdb Queries Using $wpdb->get_results & $wpdb->prepare?
  69. When/why does ‘$query->get( ‘tax_query’ );’ return empty?
  70. Changing the meta_query of the main query based on custom query_vars and using pre_get_posts
  71. Meta Query with AND & OR?
  72. How to get link and title of next and previous post on single page
  73. Create pagination and order according to alphabet
  74. wpdb get posts by taxonomy SQL
  75. Dealing with Many Meta Values, 30+
  76. How to List Events by Year and Month Using Advanced Custom Fields?
  77. What is the most efficient way of querying posts based on visits and date for current day?
  78. Is there any difference between hooks posts_where with posts_join and posts_search performance wise?
  79. Is it possible to orderby multiple meta_keys when using meta_value_num?
  80. Custom WP_Query order by post_meta and (author) user_meta
  81. wordpress query – orderby child post date
  82. Query WooCommerce orders where meta data does not exist
  83. Meta compare with date (stored as string) not working
  84. Getting attachments by meta value
  85. How many WordPress SQL Queries per page?
  86. How to display Section for certain time
  87. Add multiple value to a query variable in WordPress
  88. Ordering posts having multiple post-meta date fields
  89. Custom query_var causes displaying posts archive on front page
  90. Slow wp_enqueue_media()
  91. Multipart/formatted MySQL query problem
  92. What is the most efficient way of implementing a favorite post system?
  93. Query Custom Meta Value with Increment
  94. Remove [gallery] shortcode altogether
  95. Compare two numeric custom fields
  96. wp_dropdown_categories with multiple select
  97. Advanced Custom Fields – Query Efficiency
  98. Why does get_the_time(‘F j’) return November 30 for all posts?
  99. How Can I save multiple records in same meta key?
  100. How to get all term meta for a taxonomy – getting term_meta for taxonomy
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
  • Post Navigation Elementor
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • WPFacet multiple loop displaying duplicate content
  • Get the name of the template/*html file used
  • Fix: WordPress.DB.PreparedSQL.NotPrepared Plugin Check (PCP)
  • Removing unnecessary CSS and JS code from wp_head()
  • hexagonal image gallery. Am I on the right track? [closed]
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
© 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