How To Get Posts In WordPress by Repeater Value

In this tutorial we will get all posts from a custom post type which have a certain key and value from a repeater acf field. To do this we will create a custom function where we will check what we need in order to get the rights posts. 

Get Posts In Wordpress by Repeater Value

First of all I will create a new custom post type named "projets" using Custom Post Type plugin. Then I will add a new repeater to this post named "assign_users" -> "user". 

We will have to get all posts which are assigned to the current user id and show them in frontend. To do that we will create a new function in functions.php file. Open the file and add the following function:

function return_projects($user_id){
  $args = array(
    'post_type' => 'projects',
    'posts_per_page' => -1,
    'meta_query' => array(
      'relation'      => 'AND',
        array(
          'key' => 'assign_users_$_user',
          'compare' => '=',
          'value' => $user_id,
        )
      )
  );
  $projects = get_posts($args);
  return $projects;
}

As you can see above, this is the default wordpress function where we check in our acf repeater field if there is any post which is assigned to the current user id. If you will try the above function you will see that it does not work because is incomplete. In order to make it working we will have to add a new function which looks like the following:

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

With the above function you will see that you will be able to get any posts you need based on repeater search. The code above is not tested with multiple repeater fields but it should work. Let us know if you need any help with this implementation.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x