The posts_clauses filter in WordPress allows you to modify various query clauses at once. It covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT, fields (SELECT), and LIMIT clauses.
Usage
add_filter('posts_clauses', 'your_custom_function', 10, 2);
function your_custom_function($clauses, $query) {
// your custom code here
return $clauses;
}
Parameters
- $clauses (string[]): An associative array of the clauses for the query, which includes where, groupby, join, orderby, distinct, fields, and limits.
- $query (WP_Query): The WP_Query instance, passed by reference.
More information
See WordPress Developer Resources: https://developer.wordpress.org/reference/hooks/posts_clauses/
Examples
Exclude a specific category
Exclude posts from a specific category from the query.
add_filter('posts_clauses', 'exclude_category', 10, 2);
function exclude_category($clauses, $query) {
global $wpdb;
// Replace '5' with the ID of the category you want to exclude
$exclude_category_id = 5;
$clauses['join'] .= " LEFT JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id";
$clauses['where'] .= " AND {$wpdb->term_relationships}.term_taxonomy_id != {$exclude_category_id}";
return $clauses;
}
Order posts by word count
Order posts by word count in ascending order.
add_filter('posts_clauses', 'order_by_word_count', 10, 2);
function order_by_word_count($clauses) {
global $wpdb;
$clauses['orderby'] = "LENGTH({$wpdb->posts}.post_content) ASC";
return $clauses;
}
Exclude posts with specific meta key
Exclude posts with a specific meta key from the query.
add_filter('posts_clauses', 'exclude_meta_key', 10, 2);
function exclude_meta_key($clauses) {
global $wpdb;
$clauses['join'] .= " LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id";
$clauses['where'] .= " AND {$wpdb->postmeta}.meta_key != 'your_meta_key'";
return $clauses;
}
Show only posts with featured images
Filter the query to show only posts with featured images.
add_filter('posts_clauses', 'show_only_featured', 10, 2);
function show_only_featured($clauses) {
global $wpdb;
$clauses['join'] .= " INNER JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id";
$clauses['where'] .= " AND {$wpdb->postmeta}.meta_key = '_thumbnail_id'";
return $clauses;
}
Limit the number of posts
Limit the number of posts returned by the query.
add_filter('posts_clauses', 'limit_posts', 10, 2);
function limit_posts($clauses) {
// Set the limit to the desired number of posts
$post_limit = 5;
$clauses['limits'] = "LIMIT {$post_limit}";
return $clauses;
}