Using WordPress ‘posts_where’ PHP filter

posts_where is a WordPress PHP filter that allows you to modify the WHERE clause of a WordPress query, giving you more control over which posts are retrieved.

Usage

add_filter( 'posts_where', 'your_custom_function', 10, 2 );

function your_custom_function( $where, $query ) {
    // your custom code here
    return $where;
}

Parameters

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

More information

See WordPress Developer Resources: posts_where

Examples

Filter posts by a custom field value

Filter posts that have a custom field “featured” with the value “yes”.

add_filter( 'posts_where', 'filter_featured_posts', 10, 2 );

function filter_featured_posts( $where, $query ) {
    global $wpdb;
    $where .= " AND EXISTS ( SELECT 1 FROM {$wpdb->postmeta} WHERE post_id = {$wpdb->posts}.ID AND meta_key = 'featured' AND meta_value = 'yes' )";
    return $where;
}

Exclude posts with a specific title

Exclude posts with the title “Hello World”.

add_filter( 'posts_where', 'exclude_hello_world', 10, 2 );

function exclude_hello_world( $where, $query ) {
    global $wpdb;
    $where .= " AND {$wpdb->posts}.post_title NOT LIKE 'Hello World'";
    return $where;
}

Filter posts by word count

Filter posts with a word count greater than 500.

add_filter( 'posts_where', 'filter_by_word_count', 10, 2 );

function filter_by_word_count( $where, $query ) {
    global $wpdb;
    $where .= " AND LENGTH({$wpdb->posts}.post_content) - LENGTH(REPLACE({$wpdb->posts}.post_content, ' ', '')) + 1 > 500";
    return $where;
}

Show posts from the current month

Display posts published in the current month.

add_filter( 'posts_where', 'filter_current_month_posts', 10, 2 );

function filter_current_month_posts( $where, $query ) {
    global $wpdb;
    $current_month = date('Y-m');
    $where .= " AND {$wpdb->posts}.post_date >= '{$current_month}-01 00:00:00' AND {$wpdb->posts}.post_date <= '{$current_month}-31 23:59:59'";
    return $where;
}

Show only posts with even post IDs

Display posts with even post IDs.

add_filter( 'posts_where', 'filter_even_post_ids', 10, 2 );

function filter_even_post_ids( $where, $query ) {
    global $wpdb;
    $where .= " AND {$wpdb->posts}.ID % 2 = 0";
    return $where;
}