using posts_where for meta data on pre_get_posts
Let's say you have some code which filters posts by using pre_get_posts
e.g.
add_action( 'pre_get_posts', 'be_exclude_category_from_blog' );
function be_exclude_category_from_blog( $query ) {
if( $query-is_main_query() $query-is_home() ) {
$query-set( 'cat', '-4' );
}
}
I found a nice bit of code which enables you to further filter these posts to the last 90 days:
add_action( 'pre_get_posts', 'be_exclude_category_from_blog' );
function be_exclude_category_from_blog( $query ) {
if( $query-is_main_query() $query-is_home() ) {
add_filter( 'posts_where', 'filter_date' );
$query-set( 'cat', '-4' );
}
}
function filter_date( $where = '' ) {
$where .= " AND post_date '" . date('Y-m-d', strtotime('-90 days')) . "'";
return $where;
}
This works really well. But what if I want to use the same method to target a post's meta data instead of just post_date? Is this possible? From this answer it looks like you should do something like this:
add_action( 'pre_get_posts', 'be_exclude_category_from_blog' );
function be_exclude_category_from_blog( $query ) {
if( $query-is_main_query() $query-is_home() ) {
add_filter( 'posts_where', 'filter_date' );
$query-set( 'cat', '-4' );
}
}
function filter_date( $where = '' ) {
global $wpdb;
$where .= " AND ($wpdb-postmeta.meta_key = '_length' AND $wpdb-postmeta.meta_value = '61')";
return $where;
}
However this does not work for me, it returns zero results. Even though I know there are posts with a meta key of _length
with a value of 61
.
Could someone point me in the right direction?
Cheers
Topic posts-where pre-get-posts filters Wordpress
Category Web