为 img 标签动态添加数据属性

Dynamically Add Data Attribute to Img Tag

我希望将 "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>