Home › Forums › General Issues › Checkbox while loop if value exists
Hi folks,
I’m using a ‘checkbox’ field type on a post template. It only has one value ‘yes’ but it based around the question ‘Is this a short course?’ with one checkbox field value ‘yes’.
I’m then creating a separate page to list all the posts that have this checkbox ticked; which would list all their titles with their permalinks.
I thought, adapting what the documentation states, would work, but it doesn’t. It seems to set it on a endless while loop. Any ideas?
<?php $courses = get_posts(array(
'meta_query' => array(
array(
'key' => 'short_course', // name of custom field
'value' => '"yes"', // matches exaclty "yes", not just yes. This prevents a match for "acquired"
'compare' => 'LIKE'
)
)
));
if ( $courses ) while ( $courses ) : ?>
test
<?php endwhile; ?>
Hi @rdck
Does your code contains an endif
?
Perhaps it is not the query but a syntax error on the page?
Can you turn on DEBUG MODE in your wp-config.php
Thanks
E
Thanks for the reply @elliot, however, adding the endif; doesn’t solve it. It still is spitting out the word ‘test’ infinitely and crashing the site, rather than what is to be expected.
<?php $courses = get_posts(array(
'meta_query' => array(
array(
'key' => 'short_course', // name of custom field
'value' => '"yes"', // matches exaclty "yes", not just yes. This prevents a match for "acquired"
'compare' => 'LIKE'
)
)
));
if ( $courses ) : while ( $courses ) : ?>
test
<?php endwhile; endif; ?>
Hi @rdck
Sorry, I completely missed the issue!
The issue is that you are using a while loop which will never end!
You should be using a foreach!
Hi again @elliot
Thanks for your continual help.
My code now stands as this:
<?php $courses = get_posts(array(
'meta_query' => array(
array(
'key' => 'short_course',
'value' => '"yes"',
'compare' => 'LIKE'
)
)
));
if ( $courses ) : foreach ($courses as $course) : ?>
<a href="<?php the_permalink($course->ID); ?>">test</a>
<?php endforeach; endif; ?>
But the permalink isn’t bringing back the permalink URL… only the current page URL. Am I missing something?
And I did change
the_permalink($course->ID)
to
get_permalink($course->ID)
But made no difference…
Okay, school boy error, missed the echos 🙁
<a href="<?php echo get_permalink($course->ID); ?>"><?php echo get_the_title($course->ID); ?></a>
Many thanks for the help.
The topic ‘Checkbox while loop if value exists’ 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 Privacy Policy. If you continue to use this site, you consent to our use of cookies.