Home › Forums › Add-ons › Repeater Field › If Subfields Equals, Show Posts › Reply To: If Subfields Equals, Show Posts
Hi @fredjs and @chromasites
There are some information regarding querying subfield here: http://www.advancedcustomfields.com/resources/query-posts-custom-fields/
@fredjs first off you should never use query_posts.. it’s been shunned by developers for quite some time. Instead use either pre_get_posts filter to modify a core query or the WP_Query class to create a new query.
You have not told me the fieldname of your repeater field so in this example it’s written as “repeaterfieldname”. For the examples to work you need to replace these.
Put this in the template where you want to display the posts:
<?php
// args
$args = array(
'posts_per_page' => -1,
'post_type' => 'profiles',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'repeaterfieldname_%_year',
'compare' => '=',
'value' => '2015',
),
array(
'key' => 'repeaterfieldname_%_level',
'compare' => '=',
'value' => 'grand prize',
)
)
);
// query
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
And this should go in your themes functions.php:
// filter
function my_posts_where( $where ) {
$where = str_replace("meta_key = 'repeaterfieldname_%", "meta_key LIKE 'repeaterfieldname_%", $where);
return $where;
}
add_filter('posts_where', 'my_posts_where');
Please note that if your sub fields are in different repeaters you need to do a replace on both of these in the my_posts_where function:
// filter
function my_posts_where( $where ) {
$where = str_replace("meta_key = 'repeaterfieldname_%", "meta_key LIKE 'repeaterfieldname_%", $where);
$where = str_replace("meta_key = 'repeaterfieldname2_%", "meta_key LIKE 'repeaterfieldname2_%", $where);
return $where;
}
add_filter('posts_where', 'my_posts_where');
Try it out!
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 Privacy Policy. If you continue to use this site, you consent to our use of cookies.