Hi!
I think I understand, you’re probably trying to query by a custom field.
Looking at Example 1. from that resource page, it’s very similar to what you are trying to accomplish. Assuming your custom field is attached to some kind of query-able post type like posts
or pages
(my preference is to create a custom post type) this should be very easy.
<?php
// args
$args = array(
'posts_per_page' => -1, //get all posts
'post_type' => 'your_post_type_slug', //posts, pages, whatever the field is attached to
'meta_key' => 'listing-location', //custom field slug
'meta_value' => 'New York' //location to count
);
// query
$the_query = new WP_Query( $args ); //get WP Query using $args
$count = $the_query->post_count; //use property post_count to return the count
echo 'Location: New York';
echo 'Total listings I have with that location are '. $count;
?>
The property post_count
is available when using a WP_Query. More information here: WP_Query
Obviously this may not be the most efficient code because the location is hard coded, but maybe that works in your situation.
My advice would be to set up the listing location as a custom category/taxonomy instead of an ACF field. That way you could loop through all the available categories dynamically.
Hope this helps!
Hi Jerrel!
Can you post your code so that I can take a look at what the issue might be?
Hi Yormario, I believe you’re almost there! It looks like you are using the wrong field function for your situation.
The solution would be to use get_field()
which will allow you to get the input and store it in a variable to return.
If you want a more in depth explanation, the reason your ACF Fields are not showing in the right order is because the_field()
doesn’t return a value, but echos it. It is essentially the same as doing echo get_field();
This means the values aren’t stored and instead are echoed in the order they are called, before the filter function is returned.
More information here: https://www.advancedcustomfields.com/resources/get_field/
Also, small, but important difference you are missing the $
for the second field variable in the return statement.
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.