Using WordPress ‘posts_where_request’ PHP filter

apply_filters_ref_array is a WordPress PHP filter that allows you to modify the WHERE clause of a WordPress query. It’s especially useful for caching plugins to adjust queries before they’re executed.

Usage

To use the apply_filters_ref_array filter, you need to hook a custom function into it. Here’s a basic code example:

add_filter('posts_where_request', 'my_custom_where_filter', 10, 2);

function my_custom_where_filter($where, $query) {
    // Your custom code to modify the $where variable
    return $where;
}

Parameters

  • $where (string)
    • The WHERE clause of the query.
  • $query (WP_Query)
    • The WP_Query instance (passed by reference).

Examples

Filter Posts with Specific Tag

add_filter('posts_where_request', 'filter_posts_with_specific_tag', 10, 2);

function filter_posts_with_specific_tag($where, $query) {
    global $wpdb;
    if ($query->is_main_query()) {
        $where .= " AND {$wpdb->prefix}terms.slug = 'my-tag'";
    }
    return $where;
}

This example modifies the WHERE clause to only include posts with the ‘my-tag’ tag.

Exclude Posts with Specific Category

add_filter('posts_where_request', 'exclude_posts_with_specific_category', 10, 2);

function exclude_posts_with_specific_category($where, $query) {
    global $wpdb;
    if ($query->is_main_query()) {
        $where .= " AND {$wpdb->prefix}terms.slug != 'exclude-category'";
    }
    return $where;
}

This example modifies the WHERE clause to exclude posts with the ‘exclude-category’ category.

Filter Posts by Custom Field Value

add_filter('posts_where_request', 'filter_posts_by_custom_field', 10, 2);

function filter_posts_by_custom_field($where, $query) {
    global $wpdb;
    if ($query->is_main_query()) {
        $where .= " AND {$wpdb->prefix}postmeta.meta_key = 'custom_field_key' AND {$wpdb->prefix}postmeta.meta_value = 'custom_value'";
    }
    return $where;
}

This example modifies the WHERE clause to include only posts with a specific custom field value.

Exclude Posts Older Than 30 Days

add_filter('posts_where_request', 'exclude_posts_older_than_30_days', 10, 2);

function exclude_posts_older_than_30_days($where, $query) {
    global $wpdb;
    if ($query->is_main_query()) {
        $where .= " AND {$wpdb->prefix}posts.post_date > DATE_SUB(NOW(), INTERVAL 30 DAY)";
    }
    return $where;
}

This example modifies the WHERE clause to exclude posts older than 30 days.

Filter Posts with Specific Post Status

add_filter('posts_where_request', 'filter_posts_with_specific_status', 10, 2);

function filter_posts_with_specific_status($where, $query) {
    global $wpdb;
    if ($query->is_main_query()) {
        $where .= " AND {$wpdb->prefix}posts.post_status = 'draft'";
    }
    return $where;
}

This example modifies the WHERE clause to include only posts with the ‘draft’ status.