posts_where WordPress Filter Hook

The posts_where hook is a great way to alter the SQL query that is used to retrieve posts from the database. This can be used to change the amount of posts that are returned, or to change the order in which they are returned.

apply_filters_ref_array( 'posts_where', string $where, WP_Query $query ) #

Filters the WHERE clause of the query.


Parameters

$where

(string)The WHERE clause of the query.

$query

(WP_Query)The WP_Query instance (passed by reference).


Top ↑

More Information

  • This filter applies to the posts where clause and allows you to restrict which posts will show up in various areas of the site. Combined with restrict_manage_posts it allows you to only show posts matching specific conditions.

    Here is an example to match the restrict_manage_posts example:

    add_filter( 'posts_where' , 'posts_where' );
    
    function posts_where( $where ) {
    
    	if( is_admin() ) {
    		global $wpdb;
    		
    		if ( isset( $_GET['author_restrict_posts'] ) && !empty( $_GET['author_restrict_posts'] ) && intval( $_GET['author_restrict_posts'] ) != 0 ) {
    			$author = intval( $_GET['author_restrict_posts'] );
    		
    			$where .= " AND ID IN (SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id=$author )";
    		}
    	}
    	return $where;
    }
    

    Depending on setup, if we had a custom post type of type ‘book’ with a taxonomy (category style) of type ‘author’, this filter would allow us to only show books written by a specific author.

  • Certain functions which retrieve posts do not run filters, so the posts_where filter functions you attach will not modify the query. To overcome this, set suppress_filters to false in the argument array passed to the function. The following code sample illustrates this.
    	//some function that modifies the query
    	function useless_condition ( $where ) { return $where . ' AND 1=1 '; }
    
    	//attach your function to the posts_where filter
    	add_filter( 'posts_where' , 'useless_condition' );
    
    	//get posts AND make sure filters are NOT suppressed
    	$posts = get_posts( array( 'suppress_filters' => FALSE ) );
    	

Top ↑

Source

File: wp-includes/class-wp-query.php

View on Trac



Top ↑

Changelog

Changelog
VersionDescription
1.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More