Support

Account

Home Forums General Issues AND relation with repeater values in query

Solved

AND relation with repeater values in query

  • Hello,

    in the documentation (https://www.advancedcustomfields.com/resources/query-posts-custom-fields/) at 4 we can see how to work with queries and a subfield of a repeater field.
    Now I have a repeater field with two subfields and I tried the same way with an AND relation but it seems the relation will be ignored. The queries searchs for value of subfield A or subfield B.

    Here’s my code so far

    $meta_query[] = [
    'relation' => 'AND',
    [
    'key' => 'spielzeiten_$_datum',
    'value' => date('Ymd'),
    'type' => 'DATE',
    'compare' => '>=',
    ],
    [
    'key' => 'spielzeiten_$_datum',
    'value' => date('Ymd', strtotime('+30 days')),
    'type' => 'DATE',
    'compare' => '<=',
    ],
    [
    'key' => 'spielzeiten_$_silberfilm',
    'value' => 0,
    'compare' => '=',
    ],

    function my_posts_where( $where ) {
    $where = str_replace("meta_key = 'spielzeiten_$", "meta_key LIKE 'spielzeiten_%", $where);
    return $where;
    }
    add_filter('posts_where', 'my_posts_where');

    Somebody have a hint for me how to fix this? So the query will search for posts where the Date is between now and 30 days in future AND is not a silberfilm?

  • The problem is not with the query, the problem is with the field names. A query that searches repeaters and also matches rows on a repeater is impossible.

    The meta names of repeaters are "{$repeater_name}_{$row_index}_{$sub_field_name}"

    The documentation and function/filter you are using causes the query to ignore the {$row_index} so if any row has a matching value in the first sub field and any other row has a matching value in the other sub field then the post will match.

    The only work around that I have ever found is to use an acf/save_post action to get the values of the repeater and I store a multidimensional array in a WP option. Each element of the array is associated with the post. then I search the multidimensional array to locate the post IDs that need to be retrieved.

    
    $option = array(
      // nested array for each post
      $post_id => array(
        // nested array of values for each row of the repeater
        array(
          // field name => value pairs for each row
          'field_name_1' => 'value_1',
          'field_name_2' => 'value_2'
        )
      )
    )
    
  • Thank you for your answer. Now I also use the save_post action but I insert a new field and update the value of this field with a combination of the two other ones. In the query I use the value of the compare field and it’s working fine.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.