Turning WP_Query shortcode into slider/carousel using Slick without a plugin

Categories: Code

Tags: , ,

We can create a slider or carousel from a custom WP_Query loop easily by using Slick.

We have created a custom WP_Query shortcode in my last post. Now we are going to turn the WP_Queried loop into a carousel.

Firstly we need to download and implement the Slick jQuery and Slick CSS into your child theme. You can download latest Slick here.

  1. Create a folder in your child theme and upload ‘slick.min.css’, ‘slick-theme.min.css’ and ‘slick.min.js’ files into the created folder. In my sample code I have created a ‘css’ folder and a ‘js’ folder separately.
  2. Create a ‘custom_script.js’ file in the folder you’ve created.
  3. Copy and paste the code below into the function.php in your child theme.
1
2
3
4
5
6
7
8
9
10
11
12
13
// Load css & js scripts
function enqueue_custom_scripts() {
	//slick css to the header
	wp_enqueue_style( 'slick_css', get_stylesheet_directory_uri() . '/css/slick.min.css', array(), null, false ); 
	wp_enqueue_style( 'slick_theme_css', get_stylesheet_directory_uri() . '/css/slick-theme.min.css', array(), null, false ); 
	//slick js to the footer
	wp_register_script('slick_jquery', ( get_stylesheet_directory_uri() . '/js/slick.min.js'), array(), null, true);
	wp_enqueue_script('slick_jquery');
	//custom js to the footer
	wp_register_script('custom_jquery', ( get_stylesheet_directory_uri() . '/js/custom_script.js'), array(), null, true);
	wp_enqueue_script('custom_jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
  • Line 4-5 – implementing Slick CSS file into header.
  • Line 7-8 – implementing Slick jQuery file into footer.
  • Line 10-11 – implementing custom jQuery file into footer.

The ‘custom_script.js’ file is to input a code that will initiate the Slick into action. We will come back to it at the end of this post.

The next is to bring the WP_Query loop into your page or post with the shortcode snippet below (See my last post for more details about the shortcode).

1
[list-posts post_type="post" posts="5"]

The code will simply display an array of featured images and titles (if you have published posts in your WordPress). We can now turn these into a carousel.

  1. Wrap the shortcode with a div element and give it a class name ‘post-carousel’.
    1
    
    <div class="post-carousel">[list-posts post_type="post" posts="5"]</div>
  2. Copy and paste the jQuery code below into the ‘custom_script.js’ file.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    $(document).ready(function(){
      $('.post-carousel .post-listing').slick({
        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 1, 
        autoplay: true,
        autoplaySpeed: 2000,
      });
    });

The custom WP_Queried images and titles are now displayed as a carousel as seen in the section below. You can find more options for Slick slider/carousel here.