CMS网站经常需要使用轮播图显示一些热点内容,就像下面这个网站
第一种实现方式:下载swiper放到主题的assets目录下,网址: https://www.swiper.com.cn/
仅需要安装包中的swiper.min.css和swiper.min.js两个文件即可,放到主题的assets目录下
在后台管理端新建一个分类:图文热点,别名为:twrd
在“图文热点”目录中添加几篇文章,一定要设置特色图片,即“缩略图”
剩下的就是在主题的活儿了。
首先要在主题的functions.php中引入swiper框架
/**
* 注册样式和脚本
*/
function mytheme_register_styles() {
//加入swpier.min.css
wp_enqueue_style('swiper',get_stylesheet_directory_uri() . '/assets/swiper5.3/swiper.min.css',array(),'5.3');
//加入swiper.min.js及依赖的jquery
wp_enqueue_script('swiper-js',get_stylesheet_directory_uri() . '/assets/swiper5.3/swiper.min.js',array('jquery'),5.3,'true');
//加入style.ss
wp_enqueue_style( 'mytheme-style', get_stylesheet_uri(), array(), '1.0' );
}
add_action( 'wp_enqueue_scripts', 'mytheme_register_styles' );
在主题中的首页index.php实现图片轮播功能
<?php
if (wp_is_mobile()):
//如果是移动端,加载header-mobile.php文件
get_header('mobile');
else:
//如果是pc端,加载header-pc.php文件
get_header('pc');
endif;
?>
<?php
$args = array(
'category_name' => 'twrd',
'posts_per_page' => 5,
);
$twrd = new WP_Query($args);
?>
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<?php
if ($twrd -> have_posts() ) :
while ($twrd -> have_posts() ) : $twrd -> the_post();
?>
<div class="swiper-slide"><a href="<?php the_permalink(); ?>"></a><?php the_post_thumbnail(); ?><header><?php the_title(); ?></header></div>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
</div>
<!-- 如果需要分页器 -->
<div class="swiper-pagination"></div>
<!-- 如果需要导航按钮 -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
<?php if (have_posts()):
while (have_posts()): the_post();
the_title('<h3>','</h3>');
the_excerpt();
the_content();
endwhile;
endif;
?>
<?php get_footer(); ?>
在footer.php文件中一定要创建swiper的对象,并进行一系统设置
<!--可以写一大部分网页底部共同的代码-->
<?php wp_footer(); ?>
<?php if (is_home()): ?>
<!-- Initialize Swiper -->
<script>
(function ($) {
function readyFn() {
// Set your code here!!
var swiper = new Swiper('.swiper-container',{
loop: true, // 循环模式选项
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable: true,
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
}
});
}
$(document).ready(readyFn);
})(jQuery);
</script>
<?php endif; ?>
</body>
</html>
在wordpress5.3中,有关jquery的使用发生了变化,不能直接使用$,必须先用jQuery声明$
为了让自己的轮播图更漂亮,需要在style.css写一些样式
/* 轮播图 */
div.swiper-container {
width: 600px !important;
height: 300px !important;
}
div.swiper-slide {
position: relative;
}
div.swiper-slide a{
position: absolute;
top:0;
bottom: 0;
left:0;
right: 0;
z-index: 1000;
opacity: 0;
}
div.swiper-slide img{
position: absolute;
max-width: 100%;
max-height: 90%;
}
div.swiper-pagination{
bottom: 50px !important;
}
div.swiper-pagination .swiper-pagination-bullet{
background-color: #fff;
}
div.swiper-slide header{
position: absolute;
width: 100%;
text-align: center;
bottom: 0;
}
最后就看到了轮播图的效果