skip to Main Content

I’m trying to get a list of posts where two custom fields have the same values. I’m not using Advanced Custom Fields.

Currently, I have this:

        <?php    
        $args = array(
            'posts_per_page' => -1,
            'meta_query' => array(
                'relation' => 'OR',
                array(
                    'key' => 'close_answer_1',
                    'value' => $close_answer_1,
                    'compare' => '='
                ),
                array(
                    'key' => 'answer',
                    'value' => $close_answer_1,
                    'compare' => '='
                )
            )
        );
        $query = new WP_Query( $args );
        ?>

This is going on a POST single page.

The result of the close_answer_1 custom field is INSET

And I’m trying to get any other post where answer, the custom field is equal to INSET

2

Answers


  1. Change 'relation' => 'OR', to 'relation' => 'AND', and that will bring all the post that has both same answer in both meta keys.

    Login or Signup to reply.
  2. It should be pretty standard, as follows. You need the relation set to "AND"

    And if it doesn’t work, either your keys are wrong, or your value isn’t set?

    If you var_dump() your result, you could get a closer look.

    $meta_query = array(
        'relation' => 'AND',
        array(
            'key'     => 'close_answer_1',
            'value'   => $yourValue,
            'compare' => '=',
            'type'    => 'CHAR',
        ),
        array(
            'key'     => 'answer',
            'value'   => $yourValue,
            'compare' => '=',
            'type'    => 'CHAR',
        ),
    );
    $args = array(
        'post_type'              => array( 'post' ),
        'post_status'            => array( 'publish' ),
        'nopaging'               => true,
        'posts_per_page'         => '-1',
        'meta_query'             => $meta_query
    );
    
    // The Query
    $query = new WP_Query( $args );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search