0

I'm banging my head to the wall all day trying to figure this out.

I have two meta keys a1 and a2 with numbers inside.

I'm trying to show posts that are a2 > a1.

In a nutshell, here's what I'm trying to accomplish:

    $posts = get_posts(array(
        'post_type'         => 'post',
    
    
        'meta_query' => array(
//return both meta keys       
            array(
                'key'            => 'a1',
            ),
            array(
                'key'            => 'a2',
            ),
//only show posts that a2 meta_value is greater than a1  meta_value
            'a2' > 'a1'
        ),
        
    ));

I know it should be possible to do this somehow.

I'm not the only one in the world trying to compare whether one post's meta_key value is greater than other...

Desperately need help or any kind of solution.

3
  • 1
    note that this query if it were possible would be very slow and expensive, and that by using get_posts instead of WP_Query, suppress_filters is enabled, so the query cannot be accessed by caching plugins, ensuring the result can never be cached for performance.
    – Tom J Nowell
    Sep 15 at 16:29
  • Have you considered storing the result of a2 > a1 as meta, or a taxonomy? Then you would only need to query that. It would be faster and save you needing to filter the results with PHP. Sep 16 at 11:49
  • That's an interesting idea. My only question is how and where should I use update_post_ meta to update the results right before querying my array? So that it won't lag.
    – robert0
    Sep 16 at 11:57
2

You can't do this in the meta query I'm afraid.

You'd need to get all the relevant records in meta query, then make that comparison inside PHP, to filter out the records you don't need.

1
  • thanks, I have already done that actually, just thought I will have a clean array code that will handle all of this in one place. I guess I will have to stick to PHP comparison. Thanks.
    – robert0
    Sep 15 at 16:33

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.