【问题标题】:Dynamically Add Data Attribute to Img Tag动态添加数据属性到 Img 标签
【发布时间】:2020-04-09 20:26:30
【问题描述】:

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

【问题讨论】:

    标签: javascript php arrays wordpress custom-data-attribute


    【解决方案1】:

    您应该创建一个变量来存储索引(例如:$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>
    

    【讨论】:

    • 你好@Cadu,效果很好。它不会打印第一个索引的值。例如,它说“data-index”,但在下一个它说“data-index=1”有没有办法切换到基于 0 的索引?
    • 我已将代码更改为echo $idx。可以试试吗?
    • 刚试了一下,可惜没有任何改变。
    • 我想通了。你需要 $idx=0;一开始。我要更新问题。
    • 但是我已经在$_posts = new WP_Query($args);之后添加了;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多