Home › Forums › General Issues › Loop ALL fields within sidebar
Hi,
I’m a bit of a newbie to ACF.
I’ve setup a Group called ‘Brands’ and a Field (image ULR) called ‘Logo’. These are for Posts.
So, all posts are assigned with a single ‘logo’ image.
Within my sidebar I would like to show a list of ALL the ‘Logos’ for ALL posts within my website.
How would I create a loop to show all fields called ‘logo’?
This is how I’m showing the filed on a single post. But unsure how I create a loop within a sidebar/page.
<?php if( get_field(‘logo’) ): ?>
“></img>
<?php endif; ?>
You need to do a query to get the posts http://codex.wordpress.org/Class_Reference/WP_Query and loop through the results
$args = array(
'post_type' => 'post', // or your post type
'posts_per_page' => -1, // get them all
'meta_query' => array(
array(
'key' => 'logo',
'value' => '',
'compare' => '!='
)
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
global $post;
while ($query->have_posts()) {
$query->the_post();
// code to display fields from each post
// same as done on a single post
}
wp_reset_postdata();
}
Thanks John.
I’m getting closer but having issues outputting the image.
My echo code must be wrong. Any ideas?
<?php
$args = array(
'post_type' => 'post', // or your post type
'posts_per_page' => -1, // get them all
'meta_query' => array(
array(
'key' => 'logo',
'value' => '',
'compare' => '!='
)
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
global $post;
while ($query->have_posts()) {
$query->the_post();
echo '<img src="' . the_field('logo') . '"></img>';
}
wp_reset_postdata();
}
?>
you need to do either
?><img src="'<?php the_field('logo'); ?>'" /><?php
or
echo '<img src="' . get__field('logo') . '" />';
also img does not have a closing tag
Hi John,
You’re a genius. Thank you. It’s working perfectly.
Below is my final code for anyone else needing this fix. Note: I’ve added a hyperlink around the logo to the relevant post.
<?php $args = array(
'post_type' => 'post', // or your post type
'posts_per_page' => -1, // get them all
'meta_query' => array(
array(
'key' => 'logo',
'value' => '',
'compare' => '!='
) ) );
$query = new WP_Query($args);
if ($query->have_posts()) {
global $post;
while ($query->have_posts()) {
$query->the_post();
echo '<a href="' . get_permalink() . '">';
echo '<img src="' . get_field('logo') . '" /></a>';
}
wp_reset_postdata();
}
?>
The topic ‘Loop ALL fields within sidebar’ 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.