Subtle diagonal pinstripe pattern in light grey and cream, giving an impression of printed editorial paper

Custom WordPress Searches With wp_parse_args And Meta Query

WordPress core search is effective for matching post titles, excerpts and content, but many Australian sites need rules outside ordinary page copy. A WooCommerce store in Sydney might restrict results to products available for local pickup, while a Melbourne wholesaler may filter by supplier, depot or invoice date. Those conditions usually live in post meta rather than in the text visitors search.

wp_parse_args() provides a predictable way to merge form input with defaults, while WP_Meta_Query turns stored fields into database filters. Used with WP_Query, they can produce a focused catalogue search without hand-written SQL. The important boundary is that parsing combines values; it does not make untrusted request data safe.

This pattern builds a reusable search for an Australian WooCommerce catalogue that matches a product term and applies optional state, stock and price filters. The same approach works for property listings, job directories and custom post types where important details are stored as metadata.

Why wp_parse_args Fits Search Forms

The function accepts an array or object and returns an array. Supplied values replace matching defaults, which is ideal when a form may contain only some of its controls. A missing field can fall back to an empty string, a default sort order or a safe page size instead of becoming an unexpected query argument.

Keep argument names consistent across the form, parsing stage and query builder. For example, use search, state, stock_status and minimum_price_cents throughout the workflow. Avoid abbreviations that differ between the HTML field and PHP code, because a mismatch can leave a filter silently inactive.

One limitation deserves attention: wp_parse_args() performs a shallow merge, not a recursive one. If a default contains a nested array, a supplied nested value replaces that entire default rather than combining individual keys. Flatten top-level form arguments, or merge nested structures deliberately after parsing.

Turning Request Data Into Safe Arguments

Sanitisation should happen before the parsed array reaches the query builder. This example accepts a text search, a state from a fixed Australian list, a WooCommerce stock status and a minimum price in dollars. It stores the price as integer cents so comparisons do not depend on floating-point formatting.

$raw = wp_unslash( $_GET );

$clean = array(
    'search'             => isset( $raw['search'] ) && is_string( $raw['search'] )
        ? sanitize_text_field( $raw['search'] )
        : '',
    'state'              => isset( $raw['state'] ) && in_array(
        $raw['state'],
        array( 'ACT', 'NSW', 'NT', 'QLD', 'SA', 'TAS', 'VIC', 'WA' ),
        true
    ) ? $raw['state'] : '',
    'stock_status'       => isset( $raw['stock_status'] ) && is_string( $raw['stock_status'] )
        ? sanitize_key( $raw['stock_status'] )
        : '',
    'minimum_price_cents' => isset( $raw['minimum_price'] ) && is_numeric( $raw['minimum_price'] )
        ? max( 0, (int) round( (float) $raw['minimum_price'] * 100 ) )
        : 0,
);

$defaults = array(
    'search'              => '',
    'state'               => '',
    'stock_status'        => '',
    'minimum_price_cents' => 0,
);

$parsed = wp_parse_args( $clean, $defaults );

The function combines values but performs no sanitising, validation or authorisation itself. sanitize_text_field() suits ordinary text, while sanitize_key() suits values such as instock. The state list prevents arbitrary text from becoming a metadata filter, and the price check rejects non-numeric input. A public search should accept only expected fields and ignore unknown keys.

Dates and times require deliberate handling in Australia. Users commonly expect day-first dates such as 24/06/2025, while WordPress stores dates in the site's configured timezone. Brisbane observes Australian Eastern Standard Time without daylight saving, whereas Sydney and Melbourne move between AEST and AEDT. Keep these display rules separate from metadata filters and let WordPress handle archive date queries.

Building the Metadata Conditions

Each active filter can become a clause in a meta_query. A top-level AND relation requires a result to satisfy every populated condition. A shopper choosing NSW and in-stock products should see only products whose metadata matches both values, rather than a broader union of records.

$meta_query = array(
    'relation' => 'AND',
);

if ( '' !== $parsed['state'] ) {
    $meta_query[] = array(
        'key'     => '_delivery_state',
        'value'   => $parsed['state'],
        'compare' => '=',
    );
}

if ( '' !== $parsed['stock_status'] ) {
    $meta_query[] = array(
        'key'     => '_stock_status',
        'value'   => $parsed['stock_status'],
        'compare' => '=',
    );
}

if ( $parsed['minimum_price_cents'] > 0 ) {
    $meta_query[] = array(
        'key'     => '_base_price_cents',
        'value'   => $parsed['minimum_price_cents'],
        'compare' => '>=',
        'type'    => 'NUMERIC',
    );
}

The example uses _delivery_state for a custom field, _stock_status for WooCommerce and _base_price_cents for a dedicated numeric price field. A store may already have _price, but WooCommerce pricing can involve sale rules, tax settings and variation data. A purpose-built integer field often gives cleaner comparisons than querying a display price another plugin may change.

Only add a clause when its control contains a meaningful value. Empty strings and empty IN lists can produce misleading matches or unnecessary database work. The type value must match how the metadata is stored: use NUMERIC for integer cents and leave comparison types out for strings. For exact values such as state abbreviations, = is faster and more predictable than a broad LIKE search.

Combining Text And Metadata Filters

WordPress text search and metadata filters answer different questions. The s argument searches core post content; it does not search every custom field automatically. A product may have “Classic cotton shirt” as its title and SH-482 as its SKU, so a shopper entering the SKU needs a metadata clause when no ordinary text contains that code.

When s and meta_query are both present, WordPress applies the text requirement and the metadata requirements together. Adding a SKU clause does not create an alternative to the title search. For a catalogue that should match either field, decide whether the SKU is a replacement query or an optional filter, because that choice changes the result set significantly.

Metadata clauses can have their own OR relation. Put a nested group inside an outer AND group when a SKU or manufacturer number may match either field but the selected state must still apply. Useful comparisons include =, IN, EXISTS, NOT EXISTS, BETWEEN and numeric operators such as >=. Test NOT IN carefully with empty fields, and remember that a leading wildcard in LIKE prevents efficient index use.

Assembling the Final WP_Query

This function accepts an input array, applies defaults, validates the recognised values again and returns a ready-to-use query. It keeps post type, status and page size under developer control, so a visitor cannot request private content or an excessive number of records by adding query parameters.

function au_product_search( $input ) {
    $defaults = array(
        'search'              => '',
        'state'               => '',
        'stock_status'        => '',
        'minimum_price_cents' => 0,
    );

    $parsed = wp_parse_args( is_array( $input ) ? $input : array(), $defaults );

    $search = is_string( $parsed['search'] )
        ? sanitize_text_field( $parsed['search'] )
        : '';
    $state = in_array(
        $parsed['state'],
        array( 'ACT', 'NSW', 'NT', 'QLD', 'SA', 'TAS', 'VIC', 'WA' ),
        true
    ) ? $parsed['state'] : '';
    $stock = is_string( $parsed['stock_status'] )
        ? sanitize_key( $parsed['stock_status'] )
        : '';

    $meta_query = array( 'relation' => 'AND' );

    if ( '' !== $state ) {
        $meta_query[] = array(
            'key' => '_delivery_state', 'value' => $state, 'compare' => '=',
        );
    }

    if ( '' !== $stock ) {
        $meta_query[] = array(
            'key' => '_stock_status', 'value' => $stock, 'compare' => '=',
        );
    }

    return new WP_Query( array(
        'post_type'      => 'product',
        'post_status'    => 'publish',
        's'              => $search,
        'posts_per_page' => 12,
        'paged'          => max( 1, absint( get_query_var( 'paged' ) ) ),
        'meta_query'     => count( $meta_query ) > 1 ? $meta_query : array(),
        'orderby'        => '' !== $search ? 'relevance' : 'date',
        'order'          => 'DESC',
    ) );
}

The returned object exposes familiar properties such as have_posts(), found_posts and max_num_pages, so it integrates cleanly with templates. The function uses product as the post type for the WooCommerce example; use post, page or a registered custom post type as appropriate. If delivery state is a taxonomy concern rather than free-form metadata, a tax_query may offer cleaner archives and better indexing.

Calling the function with a request array keeps the query builder independent of transport details. The caller may use $_GET, a shortcode attribute or a REST request, but the same validation rules should apply. For REST endpoints, also check the required capability and return an appropriate error instead of exposing results the requester may not see.

Presenting Results And Search State

A results template should provide a clear route back to the form, show the applied filters and retain those values when the shopper changes page. Hidden inputs can preserve scalar values, while select controls can mark the current option as selected. Escape every reflected value with esc_attr() and every destination URL with esc_url().

Use the query's max_num_pages with paginate_links() or an appropriate pagination function. A limit of 12 or 20 products per page works well for many Australian catalogues and keeps result pages manageable on mobile connections. Calling wp_reset_post_data() after the loop prevents later template code from accidentally reusing the search query's post data.

An empty result needs a useful explanation rather than a blank grid. Offer a way to clear optional filters, preserve the search term and point visitors towards broader categories. Taxonomies are often better for product categories, brands and Australian delivery regions than repeated metadata. Australian shoppers may search by postcode, brand, SKU or local pickup option, so those fields should be validated early and stored consistently.

Hardening, Performance And Testing

wp_parse_args() is not a security control, and WP_Query should remain the boundary that turns recognised values into SQL. Never concatenate a search term into a posts_where or posts_search filter; use $wpdb->prepare() if custom SQL is genuinely required. Continue to escape output, expose only published content and avoid accepting post status or post type directly from the browser.

Performance depends on the shape of the data and the scale of the catalogue. Exact metadata matches on state or SKU are cheaper than %term% searches. WordPress indexes metadata, but many joins and repeated wildcard clauses still become costly on large stores. For high-volume catalogues, consider taxonomy tables, WooCommerce lookup tables, caching, a dedicated search service or a plugin such as Relevanssi. Profile a realistic query before adding indexes or custom tables.

Test combinations that customers and automated requests will actually send: blank fields, mixed case, quotes, SQL-like text, unexpected arrays, several states, zero prices and stock values that no product uses. Confirm whether product variations should inherit the parent product's stock metadata, and check that pagination and cached pages show the same filters. Australian stores should verify A$ amounts and the 10% GST setting separately from the raw metadata used for filtering.

Privacy and marketing rules still apply to everything surrounding the search. If the site collects customer details, assess its obligations under the Privacy Act 1988 and the Australian Privacy Principles. Commercial electronic messages fall under the Spam Act 2003, including consent and unsubscribe requirements. A search log does not need a name or email address, so avoid collecting personal information without a clear purpose.