How to sort a WP_Query by a custom meta field

The custom meta field is a number named – “mp_price”. This WP query sorts numbers from smallest to largest or get min price and sort all meta fields.

			$args = array(
			  'post_type' => 'post',
			  'post_per_page' => -1,
			  'meta_query' => array( 
				  'show_post_query' => array(
					  'key' => 'mp_price',
					  'value' => $_GET['MINprice'],
					  'compare' => '<=',
					  'type' => 'numeric',
				  ),
				  'mp_price__order_by' => array(
					  'key' => 'mp_price',
					  'type' => 'numeric',
					  'compare' => 'numeric',
				  )
			  ),
			  'orderby' => array( 'mp_price__order_by' => 'ASC' ),
			);
		
			$the_query = new WP_Query( $args );

This WP_Query can used in search queries

<form id="query-form" method="get" action="<?php echo esc_url( home_url() ); ?>">
    <input type="number" placeholder="<?php esc_html_e('Search by Max Price','theme'); ?>"
     value="<?php if(isset($_GET['MINprice'])){ echo $_GET['MINprice']; } ?>" name="MINprice">
    <input type="submit" value="Search">
</form>

How to use WP_Query

$the_query = new WP_Query( $args );
			
// The Loop
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
	$the_query->the_post(); ?>
    // Your content here
<?php }
}
/* Restore original Post Data */
wp_reset_postdata();

Leave a Reply