View Categories

How to query by attributes and price?

< 1 min read

Custom post type query by attributes and price #



function cpt_filter_by_price_and_attributes( $atts ) {
	$atts = shortcode_atts(
		[
			'post_type' => 'post-type-two',
		],
		$atts
	);
	$args = [
		'post_type'      => $atts['post_type'], // Use the correct post type
		'post_status'    => 'publish',
		'posts_per_page' => 10,
		'paged'          => 1,
		'meta_query'     => [],
		'tax_query'      => [],
	];

	// Add price filter
	$args['meta_query'][] = [
		'key'     => '_price',
		'value'   => [ 100, 200 ],
		'compare' => 'BETWEEN',
		'type'    => 'NUMERIC',
	];

	// Add color filter
	$args['tax_query'][] = [
		'taxonomy' => 'pa_size',
		'field'    => 'slug',
		'terms'    => [ 'l' ],
		'operator' => 'IN',
	];
	$args['tax_query'][] = [
		'taxonomy' => 'pa_color',
		'field'    => 'slug',
		'terms'    => [ 'black' ],
		'operator' => 'IN',
	];

	// Run the query
	$query = new WP_Query( $args );

	if ( $query->have_posts() ) {
		$output = '<ul>';
		while ( $query->have_posts() ) {
			$query->the_post();
			$output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
		}
		$output .= '</ul>';
	} else {
		$output = '<p>No Post found.</p>';
	}

	wp_reset_postdata();
	return $output;
}

add_shortcode( 'cpt_filter_by_price_and_attributes', 'cpt_filter_by_price_and_attributes' );



Scroll to Top