0

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

0

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.

  • The trouble is I can't keep manipulating query arguments, I think I need to further filter posts once I have done the first meta_query. But I don't know how to do this. E.g. first select all posts that have a value greater than 0 for _sale_price, then exclude those posts where the current time does not fall in between _sale_price_dates_from and _sale_price_dates_to. I don't think I can do this at the same time using multiple meta_query arrays. – patrickzdb Jul 29 '14 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.