Jump to content

Noob in need of help


Ricky55

Recommended Posts

Hi guys

 

I'm using WordPress and the advanced Custom Fields plugin.

 

I have a basic loop that spits out the code for a slider. I'm using the image caption to populate the href of the link.

 

Currently only the first image carries a caption and therefore a link. I need to set my code up so it uses the link when the caption exists and without the link when it doesn't.

 

The advanced custom fields plugin does have a "if field exists" but I just don't know how to write the code.

 

Posted below is my code.


<?php 
$the_query = new WP_Query(array(
'post_type' => 'slider',
'posts_per_page' => '1',
)); 
 
while ($the_query->have_posts()) :
$the_query->the_post(); ?>
 
<?php $images = get_field('image_gallery');
 
if($images) : ?>
 
<!-- Flex Slider -->
<div class="flexslider entry-thumbnail">
<ul class="slides">
<?php foreach ($images as $image) : ?>
<li><a href="<?php echo $image['caption']; ?>" data-lity><img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>"></a></li>
<?php endforeach; ?>
</ul>
</div>
 
<?php endif; endwhile;  ?>

 
 
This is the basic example the advanced custom fields plugin gives you to use the if field exists.
 
<?php if( get_field('field_name') ): ?>

    <p>My field value: <?php the_field('field_name'); ?></p>

<?php endif; ?>
Link to comment
Share on other sites

<?php
foreach($images as $image):
	$opena = !empty($image['caption']) ? '<a href="'.esc_attr($image['caption']).'" data-lity>' : '';
	$closea = !empty($image['caption']) ? "</a>" : '';
?>
<li><?= $opena; ?><img src="<?= esc_attr($image['url']); ?>" alt="<?= esc_attr($image['alt']); ?>"><?= $closea; ?></li>
<?php
endforeach;
?>

Obviously the variable assignments can be refactored into a traditional if() block instead of two ternary statements if that makes it a bit easier to read - kind of up to you.

 

You need to escape output in WordPress - it won't do it for you. Also, what's the data-lity attribute doing? You don't assign it a value anywhere that I see.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.