简体   繁体   中英

Dynamically Add Data Attribute to Img Tag

I'm looking to add "data-index= " to each img tag in the array. It should equal the number it is in the array. For example it'd print "<img class="gallery-item" data-index="1" src="<?php the_field('image'); ?>" alt=""> "<img class="gallery-item" data-index="1" src="<?php the_field('image'); ?>" alt=""> and so forth. Can someone advise how to accomplish this here is what my code looks like:

*UPDATED CODE TO REFLECT ANSWER

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>

You should create a variable to store the index (eg: $idx ) and increment it on every loop:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM