CPT Loop with ACF User Field Condition

Hello!

I have a custom post type called ‘project’. This post type has an ACF user field associated with it called “repetiture_access”. I’d like to create a list of project posts where the current user is one of the users listed in the ACF user field. I’ve got this code but it’s not working:

<Set name=curr_user>
  <Field user_field="id" />
</Set>

<Loop type="project" custom_field="repetiture_access" custom_field_compare=in custom_field_value="{Get curr_user}"  >
  <p><Field title /> (<Field repetiture_access  />)</p>
</Loop>

This Loop statement yields no results even when I have users specified in the repetiture_access field for some posts.

In my testing, getting the curr_user variable outputs 1 - no quotes. If I output the value of the ACF user field using only the Field tag, I get an array of values in quotes (i.e. [“1”,“3”,“2”]). This makes me think I may be comparing numbers to strings which is why the loop isn’t yielding any results.

As a test, this loop yields results, only posts with users in the ACF user field:

<Set name=curr_user>
  <Field user_field="id" />
</Set>

<Loop type="project" custom_field="repetiture_access"   >
  <p><Field title /> (<Field repetiture_access  />)</p>
</Loop>

What am I doing wrong?

I think the issue is with the comparison, custom_field_compare=in. In the documentation for Post Query: Custom Fields:

  • custom_field_compare - Compare using one of: “equal” (default), “not”, “before”, “before_inclusive”, “after”, “after_inclusive”

The comparison in is not in the list of supported values. This is because the custom field query is provided by WP_Query, which translates it to SQL. These latter do not support querying an array/list-like value like the ACF user field, I believe stored as JSON string.

Instead of a custom field query, there’s a way to filter the loop result based on field value. This uses the field paramater, which might be better named filter_by_field. It’s not as efficient as SQL query but it can handle non-primitive values like lists.

<Loop type=project field=repetiture_access field_compare=any_is field_value="{Get curr_user}">

Note the use of any_is, when the subject (field value) is a list.

That’s the opposite of comparison in, where the value (the second half of condition) is expected to be a list.