Support

Account

Home Forums Backend Issues (wp-admin) Sorting Admin Column with repeater Reply To: Sorting Admin Column with repeater

  • If you look you will find many topics started here about the same subject, sorting posts by the values in repeater fields. The short and ugly answer is that this cannot be done.

    The values in each repeater row are saved with a unique meta key. For example, let’s say that you have a repeater with a text sub field and you put values into three rows, the meta keys of the values are repeater_0_text, repeater_1_text, and repeater_2_text. There isn’t any logical way using SQL to create a query that will sort results based on this setup.

    I’ve found that repeaters should only be used for data that will be displayed without alteration and that a repeater should never be used when the data in them will be needed for complex operations, like sorting posts.

    I you must sort posts by these values then you will need to get creative and go beyond what ACF can do for you. We could, for example, easily sort posts by a repeater sub field if the values in that field were stored in the standard WP way for storing multiple values for a single meta_key and using an acf/save_post filter is is possible to get the values from a repeater and then store them properly. Here is an example. Please note, it is an example, it does not include all the necessary code and it may contain errors, I’m not testing this.

    
    // add an action that will run after acf is done
    add_action('acf/save_post', 'my_save_post_action', 20);
    function my_save_post_action($post_id) {
      // make sure the post is one we want to update
      if (get_post_type($post_id) != 'my-post-type') {
        return;
      }
      // set up a new meta key
      // that will hold the repeater sub field
      // in standard WP fashion
      // the meta key needs to be unique
      $meta_key = 'repeater_text_copy';
      // delete all the data form our meta key
      delete_post_meta($post_id, $meta_key);
      // now get the values from the repeater and
      // store in the new location
      if (have_rows('repeater', $post_id)) {
        while(have_rows('repeater', $post_id)) {
          the_row();
          // insert the post meta with $unique parameter set to false
          add_post_meta($post_id, $meta_key, get_sub_field('text'), false);
        }
      }
    }
    

    Now you can query posts and sort them based on the value in this new meta field.