I have a website that displays a slideshow using custom fields and the Slick carousel, using the code below.
<?php $entries = get_post_meta( get_the_ID(), '_mysite_homepage_slider_group', true );
foreach ( (array) $entries as $key => $entry ) {
$img = $title = $url = $desc = '';
if ( isset( $entry['_mysite_homepage_slider_title'] ) )
$title = esc_html( $entry['_mysite_homepage_slider_title'] );
if ( isset( $entry['_mysite_homepage_slider_caption'] ) )
$desc = wpautop( $entry['_mysite_homepage_slider_caption'] );
if ( isset( $entry['_mysite_homepage_slider_url'] ) )
$url = esc_html( $entry['_mysite_homepage_slider_url'] );
if ( isset( $entry['_mysite_homepage_slider_image_id'] ) ) {
$img = wp_get_attachment_image_url( $entry['_mysite_homepage_slider_image_id'], 'full');
}
} ?>
I'd like the user to be able to disable individual slides by clicking a checkbox in the back-end.
Simple enough, right?
So, I added a checkbox and came up with this code to drop in to my snippet. It checks to see if the checkbox is clicked. I tried placing it immediately after the foreach
line, like this:
foreach ( (array) $entries as $key => $entry ) {
// Display slides if checkbox is NOT clicked (e.g., is empty)
if ( empty( $entry['_mysite_homepage_slider_checkbox'] ) ) {
$img = $title = $url = $desc = '';
(...)
}
It kind of works — the slide doesn't show up on the page — but something's still getting through. A duplicate slide is being created.
For example, There are 4 slides in the back end. The 4th has a checkbox that is checked. On the front end, Slide #3 is displayed twice. It appears the code is outputting this:
- Slide 1
- Slide 2
- Slide 3
- Slide 3 (again!)
Where have I gone wrong?
EDIT: Final code snippet with answer, for anyone who may find this useful in the future.