将数据属性动态添加到Img标记



我希望将"data index="添加到数组中的每个img标记中。它应该等于它在数组中的数字。例如,它会打印"<img class="gallery-item" data-index="1" src="<?php the_field('image'); ?>" alt="">等等。有人能建议如何在这里实现这一点吗?我的代码是这样的:

*更新代码以反映答案

HTML

<div id="container" class="isotope" data-element="gallery-item">
<?php 
$idx=0;
$args = array(
'post_type' => 'Photos',
);
$_posts = new WP_Query($args);
?>
<?php 
if ( $_posts->have_posts() ) : while ( $_posts->have_posts() ) : $_posts->the_post(); ?>
<div class="grid-item" data-filter="<?php 
$categories = get_the_category(get_the_id());
foreach ($categories as $category){ 
echo $category->slug;}?>">
<a onClick='showDialog()' data-target="#lightbox">
<img class="gallery-item" data-index="<?php esc_attr_e( $idx ); ?>" src="<?php the_field('image'); ?>" alt="">
</a>
</div>
<?php
$idx++;
endwhile; endif;
?>
</div>

您应该创建一个变量来存储索引(例如:$idx(,并在每个循环中递增:

<div id="container" class="isotope" data-element="gallery-item">
<?php 
$args = array(
'post_type' => 'Photos',
);
$_posts = new WP_Query($args);
$idx = 0; // start the index
?>
<?php 
if ( $_posts->have_posts() ) : while ( $_posts->have_posts() ) : $_posts->the_post(); ?>
<div class="grid-item" data-filter="<?php 
$categories = get_the_category(get_the_id());
foreach ($categories as $category){ 
echo $category->slug;}?>">
<a onClick='showDialog()' data-target="#lightbox">
<img data-index="<?php echo $idx; ?>" class="gallery-item" src="<?php the_field('image'); ?>" alt="">
</a>
</div>
<?php
$idx++; // increments the index
endwhile; endif;
?>
</div>

最新更新