我正在学习编码的第一步。我在互联网上开了一些课程,现在我决定继续学习构建Wordpress儿童主题的经验。
问题是我想制作幻灯片,我在w3schools http://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_self找到了这个很酷很简单的。
太棒了!但是如果我想在Wordpress中实现它会有一些问题。
我制作了10个图像区域。每一个都是一个空间来放置我幻灯片的一张图片。代码将是这样的:
<?php get_header(); ?>
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
</script>
<div class="mySlides"><?php the_field("image"); ?></div>
<div class="mySlides"><?php the_field("image_2"); ?></div>
<div class="mySlides"><?php the_field("image_3"); ?></div>
<div class="mySlides"><?php the_field("image_4"); ?></div>
<div class="mySlides"><?php the_field("image_5"); ?></div>
<div class="mySlides"><?php the_field("image_6"); ?></div>
<div class="mySlides"><?php the_field("image_7"); ?></div>
<div class="mySlides"><?php the_field("image_8"); ?></div>
<div class="mySlides"><?php the_field("image_9"); ?></div>
<div class="mySlides"><?php the_field("image_10"); ?></div>
<a class="home-btn-left" onclick="plusDivs(-1)">❮</a>
<a class="home-btn-right" onclick="plusDivs(1)">❯</a>
</div><!-- .content-area -->
<?php get_footer(); ?>
这有一个问题:我总是要上传10张图片,因为如果我上传的图片少于10张,我会将空的自定义字段显示为空格。
由于这个问题,我决定制作一个转发器字段。所以我可以根据需要创建多少个图像子字段,而不会出现这个空字段问题。
所以代码就是这样:
<?php
// check if the repeater field has rows of data
if( have_rows('image') ):
// loop through the rows of data
while ( have_rows('image') ) : the_row();
// display a sub field value
the_sub_field('subimage');
endwhile;
else :
// no rows found
endif;
?>
但现在问题是:如何将html类应用于我的子字段?像这样,我可以制作幻灯片。
我试过这个,但它不起作用:
<?php
// check if the repeater field has rows of data
if( have_rows('image') ):
// loop through the rows of data
while ( have_rows('image') ) : the_row();
// display a sub field value
<div class="mySlides"> the_sub_field('subimage');</div>
endwhile;
else :
// no rows found
endif;
?>
你有什么建议吗?
答案 0 :(得分:1)
替换
行<div class="mySlides"> the_sub_field('subimage');</div>
使用:
?><div class="mySlides"><?php the_sub_field('subimage'); ?></div> <?php
当混合使用html和php时,你必须跳入和跳出php模式才能使代码生效。
另一种方法是使用echo在php模式下打印html:
echo '<div class="mySlides">';
the_sub_field('subimage');
echo '</div>';
答案 1 :(得分:1)
首先,请勿在此处使用the_sub_field()
。 the_sub_field()
呼应了这个领域。而不是这个,使用get_sub_field
。它检索值而不输出它。您的代码应如下所示:
// check if the repeater field has rows of data
if( have_rows('image') ):
// loop through the rows of data
while ( have_rows('image') ) : the_row();
if( get_sub_field('subimage') ) :
// display a sub field value
echo '<div class="mySlides">' . get_sub_field('subimage') . '</div>';
endif;
endwhile;
endif;
请注意if( get_sub_field('subimage') ) :
语句,以检查转发器字段中是否确实存在值。如果是,它会回应与您的get_sub_field('subimage')
函数链接的字符串。
查看here高级示例。