Home › Forums › Add-ons › Repeater Field › Query subfield value using get_posts()
I understand that there is no easy way to use get_posts to query posts whose subfields of a repeater field match a particular value, but I’m looking for a work around.
On my site, I have a CPT called “Companies”. All companies have a repeater field called “location”. The location repeater field has a relationship subfield with another CPT called “Areas”.
I’ve got category pages that display the companies that fall into them. I want to show a list of areas, and then the companies that are in those areas.
Here’s my current idea (which I haven’t been able to pull off):
I start by looping through all the areas, with a simple WP loop. Then, what I WANT to do is query the companies that are of the post_type “company”, are in the category for the current page, and whose location repeater fields have a subfield “area” that matches the area ID in the loop. So far, I have been unsuccessful at doing this bit.
Here’s my code thus far:
$area_args = array(
'post_type'=>'area'
);
// The Query
$areas = new WP_Query( $area_args );
// If there are ANY areas to be listed
if ( $areas->have_posts() ) {
echo '<ul class="list_style_none">';
while ( $areas->have_posts() ) {
$areas->the_post();
// Get companies by area
$companies = get_posts(array(
'post_type' => 'company',
'category' => $category_id,
'meta_query' => array(
array(
'key' => 'location_%_area', // name of custom field
'value' => '"' . get_the_ID() . '"', // gets AREA in current loop
'compare' => 'LIKE'
)
)
));
if ($companies) {
echo '<li class="area_section">';
$thumb_size = 'full';
echo '<h3 class="'. $page_slug . '">' . get_the_title() . '</h3>';
echo '<ul class="company_listings list_style_none col span_1_of_3">';
foreach ($companies as $company) {
echo '<li class="company_link">';
echo '<a href="' . get_permalink($company->ID) . '" >';
echo get_the_title($company->ID). '</a></li>';
}
echo '<div class="clearboth"></div></ul><div class="clearboth"></div></li>';
}
}
echo '</ul>';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>
Any help will be much appreciated!
Hi @anniesexton
Can you please read over this thread:
http://support.advancedcustomfields.com/forums/topic/reverse-query-relationship-subfield-which-is-nested-in-a-repeater-field/
I think this will provide the solution you are after.
Thanks
E
The topic ‘Query subfield value using get_posts()’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.