John Davidson

php - Filter query based on min and max price for custom post type

0 comments
Message:


I have an ACF field called price. price is assigned to the vehicle post type.


I also have a filter which allows users to show vehicle's based on defined min price and max price.


I'm trying to showcase the results of the vehicle's which fall between the defined min price and max price range.


Here's what I have so far:




<?php

// get data from url
$min_price = $_GET['min-price'];
$max_price = $_GET['max-price'];

global $post;

$args = array(
'post_type' => 'vehicle',
'post_status' => 'publish',
'orderby' => 'publish_date',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'price',
'value' => array($min_price, $max_price),
'compare' => 'BETWEEN',
'type' => 'numeric',
)
),
);


$query = new WP_Query( $args );

if($query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
$price = get_field("price");
$price = preg_replace("/[^0-9]/", "", $price);

echo the_title();
endwhile; wp_reset_postdata();

else : ?>
<h2><?php _e("no posts found"); ?></h2>
<?php endif; ?>


?>


My Answer:
php
$args = array(
'post_type' => 'vehicle',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'price',
'value' => array( $min_price, $max_price ),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Display vehicle information here
}
} else {
// No vehicles found
}

wp_reset_postdata();


In the above code, replace `$min_price` and `$max_price` with the minimum and maximum price values set by the user in the filter. This query will retrieve all vehicle posts that have a price between the defined min and max price range.

Rate this post

3 of 5 based on 5352 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us