Using WordPress ‘posts_clauses_request’ PHP filter

posts_clauses_request is a WordPress PHP filter that allows you to modify all query clauses at once, which is useful for caching plugins. It covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT, fields (SELECT), and LIMIT clauses.

Usage

add_filter('posts_clauses_request', 'my_custom_posts_clauses_request', 10, 2);
function my_custom_posts_clauses_request($clauses, $query) {
    // your custom code here
    return $clauses;
}

Parameters

  • $clauses (array) – An associative array containing the various SQL query clauses.
  • $query (WP_Query) – The WP_Query object.

More information

See WordPress Developer Resources: posts_clauses_request

Examples

Remove Distinct Clause

Remove the DISTINCT clause from the SQL query.

add_filter('posts_clauses_request', 'remove_distinct_clause', 10, 2);
function remove_distinct_clause($clauses) {
    $clauses['distinct'] = '';
    return $clauses;
}

Change Order By Clause

Change the ORDER BY clause to order posts by title.

add_filter('posts_clauses_request', 'order_by_title', 10, 2);
function order_by_title($clauses) {
    $clauses['orderby'] = 'post_title ASC';
    return $clauses;
}

Modify Join Clause

Modify the JOIN clause to include a custom table.

add_filter('posts_clauses_request', 'modify_join_clause', 10, 2);
function modify_join_clause($clauses) {
    global $wpdb;
    $clauses['join'] .= " LEFT JOIN {$wpdb->prefix}my_custom_table ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}my_custom_table.post_id";
    return $clauses;
}

Add Custom Where Clause

Add a custom WHERE clause to filter posts by a specific value in a custom table.

add_filter('posts_clauses_request', 'add_custom_where_clause', 10, 2);
function add_custom_where_clause($clauses) {
    global $wpdb;
    $clauses['where'] .= " AND {$wpdb->prefix}my_custom_table.custom_value = 'desired_value'";
    return $clauses;
}

Limit the Number of Posts

Limit the number of posts returned by the query.

add_filter('posts_clauses_request', 'limit_posts', 10, 2);
function limit_posts($clauses) {
    $clauses['limits'] = 'LIMIT 5';
    return $clauses;
}