Exciting News! Flipper Code is now WePlugins! Same commitment to excellence, brand new identity.

How to use posts_clauses filter in WordPress

Sandeep Kumar Mishra
Sandeep Kumar Mishra
July 9, 2022
5 minutes read

posts_clauses filter

Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT, fields (SELECT), and LIMIT clauses.

apply_filters_ref_array( 'posts_clauses', string[] $clauses, WP_Query $query )

Description

This is filter hook , its filter all query clauses at once, for convenience.
Its consists of two parameter, one is $required and another is $query Object.

The posts_clauses filter runs before the query gets executed and is essentially the sum of all filters that run immediately before it. So it should be used if you don’t intend to let another plugin override it, or if you need to alter several different parts of the query at once. If you’re only modifying a particular clause, you should probably use one of these clause-specific filters:

* posts_where_paged
* posts_groupby
* posts_join_paged
* posts_orderby
* posts_distinct
* post_limits
* posts_fields

Parameters

  • $clauses : (string[]) Associative array of the clauses for the query.
    ‘where’
    (string) The WHERE clause of the query.
    ‘groupby’
    (string) The GROUP BY clause of the query.
    ‘join’
    (string) The JOIN clause of the query.
    ‘orderby’
    (string) The ORDER BY clause of the query.
    ‘distinct’
    (string) The DISTINCT clause of the query.
    ‘fields’
    (string) The SELECT clause of the query.
    ‘limits’
    (string) The LIMIT clause of the query.
  • $query : (WP_Query) The WP_Query instance (passed by reference).

Live Example

To run the hook, copy the example below.

$posts_clauses = apply_filters( 'posts_clauses', $clauses, $query ); 
                         
if ( !empty( $posts_clauses ) ) { 
                         
   // everything has led up to this point... 
                         
} 
   

The following example is for adding a hook callback.

// define the posts_clauses callback 
function filter_posts_clauses( $clauses, $query  ) { 
    // make filter magic happen here... 
    return $clauses; 
}; 
         
// add the filter 
add_filter( 'posts_clauses', 'filter_posts_clauses', 10, 1 ); 

To remove a hook callback, use the example below.

// remove the filter 
remove_filter( 'post_password_required', 'filter_post_password_required', 10, 2 );  

 

Explore the latest in WordPress

Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.