I am trying to use wordpress to add images to my bootstrap carousel, I have attempted a foreach loop and then try to output each part of the array i want into the correct parts of the carousel however it doesn't seem to work.
Here is the code i'm using
<?php
$args = array(
'post_type' => 'attachment',
'orderby' => 'menu_order',
'order' => ASC,
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
);
$attachments = get_posts($args);
$imageURL = array();
?>
<!-- Content -->
<div class="container">
<div class="row carousel-row">
<div class="col-md-12">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<?php $i=0; foreach ($attachments as $imageURL) { ?>
'<div class="item <?php if ($i == 0) { echo 'active'; } ?>" style="background-size:cover; background:url('<?php echo $imageURL[guid]; ?>') no-repeat center;">
<div class="carousel-caption">
<h4><?php echo $imageURL[post_excerpt];?></h4>
</div>
</div>
<?php $i++; } ?>
</div>
</div>
On this line you have an extra apostrophe at the beginning:
'<div class="item <?php if ($i == 0)
It should read:
<div class="item <?php if ($i == 0)
To make:
<div class="carousel-inner">
<?php $i=0; foreach ($attachments as $imageURL) { ?>
<div class="item <?php if ($i == 0) { echo 'active'; } ?>" style="background-size:cover; background:url('<?php echo $imageURL[guid]; ?>') no-repeat center;">
<div class="carousel-caption">
<h4><?php echo $imageURL[post_excerpt];?></h4>
</div>
</div>
<?php $i++; } ?>
</div>
And here's a refined version using the php ternary operator and the shortcut <?= instead of <?php echo :
<div class="carousel-inner">
<?php $i=0; foreach ($attachments as $imageURL) { ?>
<div class="item <?= ($i == 0 ? 'active' : '') ?>" style="background-size:cover; background:url('<?= $imageURL[guid] ?>') no-repeat center;">
<div class="carousel-caption">
<h4><?= $imageURL[post_excerpt] ?></h4>
</div>
</div>
<?php $i++; } ?>
</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.