Wp_Query : Filter posts by comparing two meta keys

Suppose I have two meta keys A and B for wordpress post. I need to get all posts where values of A != B using Wp_Query. I could only find codes to compare multiple keys and then do a AND/OR relation. Any ideas? Thanks

$args = array(
                'post_type' => 'product',
                'posts_per_page' => 100, 
                'paged' => $page
              )

$data= new WP_Query( $args ); 

Related posts

2 comments

  1. Please try like this:

    $args = array(
        'post_type' => 'product',
        'meta_query' => array(
                'relation' => 'AND',
                array(
                        'key' => 'A',
                        'value' => '1',
                        'compare' => '='),
                array(
                        'key' => 'B',
                        'value' => '1',
                        'compare' => '!=')
                )
    );
    $data = new WP_Query($args);
    
  2. You can go in this way. Get values of both your meta keys and store those values in your variables like ($a , $b respectively), then have a check on those values

    if($a != $b) {$c = $a;} //If content of a is not of same as b $c contains meta value of a meta key
    

    Now comes the query section.

      $args = array(
                'post_type' => 'product',
                'posts_per_page' => 100, 
                'paged' => $page'
                'meta_key'     => 'a',
                'meta_value'   => $c,
              )
    
          $data= new WP_Query( $args ); 
    

    Give it a try it will work for you.

    Note: a, b and c meta keys and variables are just for example purposes, use your own meta key and meta values to get results that suits you.

Comments are closed.