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


I doubt that ever worked by itself. WP_Query operates on posts database table. On the bottom SQL level to make use of post metadata you need to not only say what metadata you are looking for, but also instruct MySQL how metadata table connects to your posts table (JOIN realm).

I would attempt to keep manipulating query arguments for starters, it doesn't seem like your conditions are that complicated (from what you quoted at least).

PS also don't forget to remove your filters after, or you are messing up other queries.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.