S
S
Slava_Fame2019-07-26 09:36:34
JavaScript
Slava_Fame, 2019-07-26 09:36:34

How to programmatically create an id for an element?

Good afternoon. I have a loop that displays slides (owl-carousel2 library) with information about doctors. And for each slide (class doctors_slider__item) I need to create a unique ID for the element, so that later I can refer to it via another link on the same page and open the desired doctor. Actually, here is the code:

<!-- Сам слайдер -->
    <div id="doctors_slider" class="owl-carousel owl-theme doctor_slider">
            <?php 
                $args = array(
                    'post_type' => 'Specialists',
                    'post_per_page' => -1,
                    'order' => 'asc',
                );
                $specialists = new WP_Query( $args ); 

                if( $specialists->have_posts() ) {
                    while ($specialists->have_posts() ) {
                    $specialists->the_post(); ?>
             <!-- Определенный слайд, которому надо присвоить ID -->
                        <div class="doctors_slider__item" id="">

                        </div>
                    <?php } 
                        wp_reset_postdata();
                    }?>
                </div>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene Chefranov, 2019-07-26
@Slava_Fame

JS and jQuery tags have nothing to do with it. You just need to output the counter in the php loop. Like this:

<?php 
  $counter = 0;
  while (have_posts()) : the_post(); $counter++ 
?>
<div id="slide-<?php echo $counter; ?>"></div>
<?php endwhile; ?>

S
Stalker_RED, 2019-07-26
@Stalker_RED

Well, give them an id in the same cycle.
doc_1, doc_2, doc_3... or something like that.

A
Alexander, 2019-07-26
@lebonnet

<?php
$html = '<div id="doctors_slider" class="owl-carousel owl-theme doctor_slider">';

$specialists = new WP_Query([
    'post_type' => 'Specialists',
    'post_per_page' => -1,
    'order' => 'asc',
]);

$specialistsId = 1;

while ($specialists->have_posts()) {
    $specialists->the_post();

    $html .= <<<HTML
<div class="doctors_slider__item" data-id="{$specialistsId}">

</div>
HTML;
    $specialistsId++;
}
wp_reset_postdata();
$html .= '</div>';

echo $html;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question