Using WordPress ‘query_string’ PHP filter

query_string is a WordPress PHP filter that was used to modify the query string before parsing.

This filter has been deprecated, and it is recommended to use the ‘query_vars’ or ‘request’ filters instead.

Usage

apply_filters_deprecated( 'query_string', string $query_string )

Parameters

  • $query_string (string)
    • The query string to modify.

Examples

Removing a specific category from query results

function exclude_category( $query_string ) {
    return $query_string . '&cat=-5'; // Exclude category with ID 5
}
add_filter( 'query_string', 'exclude_category' );

This code snippet excludes the category with ID 5 from the query results by appending &cat=-5 to the query string.

Changing posts per page for a custom post type

function custom_post_type_posts_per_page( $query_string ) {
    return $query_string . '&post_type=product&posts_per_page=12'; // Change the number of products displayed per page
}
add_filter( 'query_string', 'custom_post_type_posts_per_page' );

This example modifies the query string to change the number of products displayed per page to 12 for the ‘product’ custom post type.

Filtering posts by a custom meta value

function filter_posts_by_meta( $query_string ) {
    return $query_string . '&meta_key=rating&meta_value=5'; // Show only posts with a meta value of 5 for the 'rating' meta key
}
add_filter( 'query_string', 'filter_posts_by_meta' );

In this example, the query string is modified to filter posts that have a meta value of 5 for the ‘rating’ meta key.

Excluding posts with a specific tag

function exclude_tag( $query_string ) {
    return $query_string . '&tag=-featured'; // Exclude posts with the 'featured' tag
}
add_filter( 'query_string', 'exclude_tag' );

This code snippet excludes posts with the ‘featured’ tag from the query results by appending &tag=-featured to the query string.

Ordering posts by a custom field value

function order_posts_by_custom_field( $query_string ) {
    return $query_string . '&meta_key=price&orderby=meta_value_num&order=ASC'; // Order posts by the 'price' custom field, in ascending order
}
add_filter( 'query_string', 'order_posts_by_custom_field' );

This example modifies the query string to order posts by the ‘price’ custom field value in ascending order.