Support

Account

Home Forums Add-ons Repeater Field Query Last Row of a Repeater Field Reply To: Query Last Row of a Repeater Field

  • There isn’t any way to do a query based on the last row of a repeater field. In order to do that you would need to have the same number of rows in every repeater and you’d need to replace the % in the query with the row number. For example, if a post has 5 rows the you’d query for ‘record_4_date_in’.

    Querying by and ordering by repeater sub fields is always problematic and inconsistent. Rather than try to do this I’ve found that creating a consistent field that can be used is a better solutions. For example, lets say that you want to sort your posts by the last date_in sub field.

    
    add_filter('acf/update_value/name=record', 'my_create_a_usable_field', 10, 3);
    function my_create_a_usable_field($value, $post_id, $field) {
      // $value will hold a nested array with the rows of the repeater
      if (!is_array($value)) {
        // the repeater is empty, bail early
        return $value;
      }
      $last_row = end($value);
      $date_in = $last_row['date_in'];
      // now put it into a different field
      // this field can be used in queries for filtering and sorting
      update_post_meta($post_id, 'filterable_date_in', $date_in);
    }
    

    Please not that you may need to do more with the value, for example, converting it into correct MySQL date format. I’m not sure what the value of a date field will be at this point. At any rate, this is a little more work, but gives you what is needed in a form that’s usable.