Using WordPress ‘posts_where_paged’ PHP filter

The posts_where_paged filter allows you to modify the WHERE clause of a WordPress query, specifically when dealing with paging queries.

Usage

add_filter('posts_where_paged', '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_paged

Examples

Exclude specific post IDs from the query

This example excludes posts with the IDs 5, 12, and 18 from the query.

add_filter('posts_where_paged', 'exclude_specific_post_ids', 10, 2);

function exclude_specific_post_ids($where, $query) {
    global $wpdb;
    $exclude_ids = array(5, 12, 18);
    $where .= " AND {$wpdb->posts}.ID NOT IN (" . implode(',', $exclude_ids) . ")";
    return $where;
}

Show only posts containing a specific keyword

This example filters the query to show only posts containing the word “example”.

add_filter('posts_where_paged', 'filter_posts_by_keyword', 10, 2);

function filter_posts_by_keyword($where, $query) {
    global $wpdb;
    $keyword = "example";
    $where .= " AND {$wpdb->posts}.post_content LIKE '%{$keyword}%'";
    return $where;
}

Exclude posts older than 30 days

This example filters the query to show only posts that are less than 30 days old.

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

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

Show only posts from a specific author

This example filters the query to show only posts by the author with the ID 3.

add_filter('posts_where_paged', 'filter_posts_by_author', 10, 2);

function filter_posts_by_author($where, $query) {
    global $wpdb;
    $author_id = 3;
    $where .= " AND {$wpdb->posts}.post_author = {$author_id}";
    return $where;
}

Show only posts with a specific post format

This example filters the query to show only posts with the “gallery” post format.

add_filter('posts_where_paged', 'filter_posts_by_post_format', 10, 2);
function filter_posts_by_post_format($where, $query) {
    global $wpdb;
    $post_format = "gallery";
    $where .= " AND {$wpdb->posts}.ID IN (SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id = (SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE taxonomy = 'post_format' AND term_id = (SELECT term_id FROM {$wpdb->terms} WHERE slug = 'post-format-{$post_format}')))";
    return $where;
}