Support

Account

Home Forums Add-ons Repeater Field Get users which contain specific value in the repeater Reply To: Get users which contain specific value in the repeater

  • There is an example on this page for queries based on sub fields for posts https://www.advancedcustomfields.com/resources/query-posts-custom-fields/ and the same principle could be applied to a user query https://codex.wordpress.org/Class_Reference/WP_User_Query.

    I personally don’t like that option and find that it’s one of the repeater fields shortcomings. My personal preference is to create an acf/save_post filter that takes the content for the repeater and puts it into standard WP meta fields in the database so that I can search for them without all the extra overhead. An extremely simple example of this with a repeater would be…

    
    add_action('acf/save_post', 'copy_repeater_to_standard')'
    function copy_repeater_to_standard($post_id) {
      if (substr($post_id, 0, 5) != 'user_') {
        // not a user, bail
        return;
      }
      $repeater = 'my_repeater'; // name of repeater field
      $sub_field = 'my_sub_field'; // name of sub field
    
      // the name of the new field. This is not an acf field
      // just a custom user meta field
      // that can be used for searching
      $new_field = 'converted_sub_field';
    
      $user_id = intval(substr($post_id, 5));
    
      // first step is to delete any existing content from the new field
      delete_user_meta($user_id, $new_field);
      
      // now add content from the repeater
      
      // an array to hold the values we've added
      // because there is no point in saving them twice
      $stored = array();
      
      if (have_rows($repeater, $post_id)) {
        while (have_rows($repeater, $post_id)) {
          the_row();
          $value = get_sub_field($sub_field, $post_id);
          if ($value && !in_array($value, $stored)) {
            $stored[] = $value;
            // last parameter is false so that multiple values will be stored
            add_post_meta($user_id, $new_field, $value, false);
          }
        }
      }
    }
    

    in this case it is specific to a user, but could also be used for posts and terms by using the correct functions.

    This took me only a few minutes to write and it may store a bit more in the db, but I’ve save myself a lot of trouble. Also, the queries on this new field will be much faster than the like queries that are needed to search a repeater sub field so it improves site performance.