Owl Carousel是我比较喜欢的一款carousel插件,responsive效果很好,支持触摸设备,选项灵活,鼠标拖拽就能滚动图片。本文就以WordPress内置Gallery为例来展示Owl Carousel的用法。
目录
Owl Carousel效果图

更多demo请到官网查看。
WordPress Gallery增加Carousel效果
用Owl Carousel控制WordPress Gallery的图片,只需要增加一些css和js。WordPress通过名为gallery的shortcode输出图片,根据html结构传递正确的selector给owl carousel,并移除gallery产生的br标签,就能达到carousel效果。具体步骤如下,所有代码放在主题的functions.php中。
你可以直接下载源代码,或者继续阅读,该代码适用于twentytwelve主题
[download id=56]
加载css和js
function owl_js_css(){
if( gallery_shortcode_exists() ){
wp_enqueue_style( 'owl-carousel', get_template_directory_uri() . '/owl-carousel/owl.carousel.css' );
wp_enqueue_style( 'owl-carousel-theme', get_template_directory_uri() . '/owl-carousel/owl.theme.css' );
wp_enqueue_script( 'owl-carousel', get_template_directory_uri() . '/owl-carousel/owl.carousel.js', array( 'jquery' ) );
}
}
add_action( 'wp_enqueue_scripts', 'owl_js_css' );初始化owl carousel
// 打印初始化owl carousel的js脚本
function owl_init(){
if( gallery_shortcode_exists() ) { ob_start(); ?>
<script type="text/javascript">
jQuery(document).ready(function($){
$(".gallery").find('br').remove();
$(".gallery").owlCarousel({
navigation: true,
pagination: true,
paginationNumbers: true,
items:3
});
});
</script><?php
$content = ob_get_clean();
$content = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $content);
echo $content;
}
}
add_action( 'wp_footer', 'owl_init' );输出样式
样式会根据每个主题的不同有所区别,核心要点是owl carousel会自动控制容器宽度以达到自适应效果,所以将容器上的宽度设定都去掉。
// 输出一些css样式,不同主题可能不一样
function owl_extra_style(){
if( gallery_shortcode_exists() ) { ob_start(); ?>
<style type="text/css">
.gallery-item{
width:auto !important;
float:none !important;
}
.grabbing .gallery-item a{cursor:inherit;}
</style>
<?php
$content = ob_get_clean();
$content = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $content);
echo $content;
}
}仅在shortcode存在时加载
上面的代码片段中用到一个gallery_shortcode_exists函数判断gallery shortcode是否存在。
// 检测内容里是否有gallery短代码
function gallery_shortcode_exists(){
global $post;
if( !isset( $post ) ) return false;
if( has_shortcode( $post->post_content, 'gallery' ) )
return true;
return false;
}完结。以后还会介绍如何将owl carousel应用到woocommerce中。
是按需加载吗?
shortcode存在时加载
前來支持一下~似乎很厲害的樣子~