以下示例使用了光滑的轮播。请阅读他们的文档以适应您的需求。 https://kenwheeler.github.io/slick/.
PHP 部分将代码放入您的functions.php 文件中
function carousel_required_scripts() {
wp_enqueue_style('slick-styles','//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css');
wp_enqueue_script('slick','//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js',array('jquery'));
// Create js file in your theme and use it to customize your carousel
wp_enqueue_script('slick-settings', get_stylesheet_directory_uri().'/assets/js/slick-settings.js',array('slick'));
}
add_action('wp_enqueue_scripts','carousel_required_scripts');
//Shortcode output
function my_product_shortcode( $atts, $content) {
$output[] = carousel_get_products( $atts );
return sprintf(
'<div class="slick-carousel-wrap woocommerce">%s</div>',
implode( '', $output )
);
}
// Custom query where we can use custom attributes from our shortcode
function carousel_get_products($atts) {
global $woocommerce_loop;
$atts = shortcode_atts(
array(
'total-items' => '5', // Default value if we dont set
), $atts
);
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $atts['total-items'],
);
$output = '';
ob_start();
$products = new WP_Query( $args );
if ( $products->have_posts() ) :
while ( $products->have_posts() ) : $products->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;
endif;
wp_reset_postdata();
$output = ob_get_clean();
return $output;
}
// Register our shortcode. Usage example: [mycarousel total-items="10"]
function mycarousel_shortcodes_init() {
add_shortcode( 'mycarousel', 'my_product_shortcode' );
}
add_action( 'init', 'mycarousel_shortcodes_init' );
jQuery 部分
jQuery(function($) {
$('.slick-carousel-wrap').slick({
dots: true, // default settings if responsive not set
infinite: false, // default settings if responsive not set
speed: 300, // default settings if responsive not set
slidesToShow: 3, // default settings if responsive not set
slidesToScroll: 1,// default settings if responsive not set
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
});