Back to Snippets

Optimized WP_Query with Meta and Tax Filters

PHP Database & Queries April 6, 2026

Build performant WP_Query with combined meta and taxonomy filters, numeric ordering, and no_found_rows optimization.

Snippet Stats

Lines 44
Characters 1,104
Read 2 mins
php • 44 lines
/**
 * Query featured products in a specific category.
 *
 * Uses no_found_rows for performance when pagination isn't needed.
 */
$args = array(
    'post_type'      => 'product',
    'posts_per_page' => 12,
    'no_found_rows'  => true,  // Skip SQL_CALC_FOUND_ROWS for performance.
    'meta_query'     => array(
        'relation' => 'AND',
        array(
            'key'     => '_featured',
            'value'   => 'yes',
            'compare' => '=',
        ),
        array(
            'key'     => '_price',
            'value'   => 0,
            'compare' => '>',
            'type'    => 'NUMERIC',
        ),
    ),
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => 'electronics',
        ),
    ),
    'orderby' => 'meta_value_num',
    'meta_key' => '_price',
    'order'   => 'ASC',
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) :
        $query->the_post();
        // Render your template.
    endwhile;
    wp_reset_postdata();
endif;

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
PHP
This snippet provides a custom WordPress hook to validate user registration, ensuring that users meet specific criteria before being allowed to regist...

WordPress Custom Hook For User Registration Validation

PHP
Create a custom database table with dbDelta on theme activation. Includes proper charset, indexes, and an insert helper function.

Create a Custom Database Table