How to Adding a Responsive jQuery Slider to Your WordPress Theme

[easy-social-share counters=0 style="button"]

flexslider

There are some data files here we’re interested by, mostly:

  • flexslider.css
  • images/bg_direction_nav.png
  • jquery.flexslider-min.js

they are almost all we actually need from the Flex Slider download and read.

Step 1 Setting Up the Files

Let’s move those three data files from the above into our theme’s directories right now. Dependent upon your themes and start-up it is easy to place the data files where ever you would just like, you need to notice of wherever those data files are sourced/referenced and also modify the code to fit their brand new area.

For the reason on this article, we will make use of the default Twenty Eleven theme. In theInc/ directories, set up a brand new file folder known as slider. There, let’s set up a couple of folders:

  • css
  • pictures
  • js

Lets add flexslider.css in the css file folder, bg_direction_nav.png in thepictures file folder or jquery.flexslider-min.js in the, you suspected it,js file folder.

Notice : Basically I would likely place all these in css/images/js folders all through the theme’s website directory with different data files but then in order to make this article ‘universal’ , we’re organizing our data files in this way. In case you are knowledgeable with Word Press theme development make sure you personally manage your own data files.

Right now we’re going down to generate two more data files in the slider file folder:

  • slider .php – creates the slider’s website template & loads the slider’s data files
  • slider_post_type.php – creates the slider post type

You can will have aslider file folder that look something similar to this:

slider_folder

Before we go along, open the functions.php file folder and also attach the following 2 lines, which can loading the two.php data files we simply created:

// Create Slider Post Type

require( get_template_directory() . '/inc/slider/slider_post_type.php' );

// Create Slider

require( get_template_directory() . '/inc/slider/slider.php' );

Right now . . . let’s get started coding!

Step 2 Slider Post Type

The first thing we’re able to try is set up a custom post type that will actually hold almost all our slides. Custom Post Types were developed in WordPress 3.0 as they are possibly the coolest looking thing to at any time should happen to the world-wide ( too much ? I simply like to them ).

Open slider_post_type.php and then insert the following code to set up the slide custom post type:

<?php



// Create Custom Post Type



    function register_slides_posttype() {

        $labels = array(

            'name'              => _x( 'Slides', 'post type general name' ),

            'singular_name'     => _x( 'Slide', 'post type singular name' ),

            'add_new'           => __( 'Add New Slide' ),

            'add_new_item'      => __( 'Add New Slide' ),

            'edit_item'         => __( 'Edit Slide' ),

            'new_item'          => __( 'New Slide' ),

            'view_item'         => __( 'View Slide' ),

            'search_items'      => __( 'Search Slides' ),

            'not_found'         => __( 'Slide' ),

            'not_found_in_trash'=> __( 'Slide' ),

            'parent_item_colon' => __( 'Slide' ),

            'menu_name'         => __( 'Slides' )

        );



        $taxonomies = array();



        $supports = array('title','thumbnail');



        $post_type_args = array(

            'labels'            => $labels,

            'singular_label'    => __('Slide'),

            'public'            => true,

            'show_ui'           => true,

            'publicly_queryable'=> true,

            'query_var'         => true,

            'capability_type'   => 'post',

            'has_archive'       => false,

            'hierarchical'      => false,

            'rewrite'           => array( 'slug' => 'slides', 'with_front' => false ),

            'supports'          => $supports,

            'menu_position'     => 27, // Where it is in the menu. Change to 6 and it's below posts. 11 and it's below media, etc.

            'menu_icon'         => get_template_directory_uri() . '/inc/slider/images/icon.png',

            'taxonomies'        => $taxonomies

        );

        register_post_type('slides',$post_type_args);

    }

    add_action('init', 'register_slides_posttype');

Custom Post Type installed ! Below that we will insert the metabox and where you will find a area for the Link that the slide will need to url to. We’re right now going to copy the following large walls of code:

// Meta Box for Slider URL



    $slidelink_2_metabox = array(

        'id' => 'slidelink',

        'title' => 'Slide Link',

        'page' => array('slides'),

        'context' => 'normal',

        'priority' => 'default',

        'fields' => array(





                    array(

                        'name'          => 'Slide URL',

                        'desc'          => '',

                        'id'                => 'codituts_slideurl',

                        'class'             => 'codituts_slideurl',

                        'type'          => 'text',

                        'rich_editor'   => 0,           

                        'max'           => 0            

                    ),

                    )

    );         



    add_action('admin_menu', 'codituts_add_slidelink_2_meta_box');

    function codituts_add_slidelink_2_meta_box() {



        global $slidelink_2_metabox;       



        foreach($slidelink_2_metabox['page'] as $page) {

            add_meta_box($slidelink_2_metabox['id'], $slidelink_2_metabox['title'], 'codituts_show_slidelink_2_box', $page, 'normal', 'default', $slidelink_2_metabox);

        }

    }



    // function to show meta boxes

    function codituts_show_slidelink_2_box()  {

        global $post;

        global $slidelink_2_metabox;

        global $codituts_prefix;

        global $wp_version;



        // Use nonce for verification

        echo '<input type="hidden" name="codituts_slidelink_2_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';



        echo '<table class="form-table">';



        foreach ($slidelink_2_metabox['fields'] as $field) {

            // get current post meta data



            $meta = get_post_meta($post->ID, $field['id'], true);



            echo '<tr>',

                    '<th style="width:20%"><label for="', $field['id'], '">', stripslashes($field['name']), '</label></th>',

                    '<td class="codituts_field_type_' . str_replace(' ', '_', $field['type']) . '">';

            switch ($field['type']) {

                case 'text':

                    echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" /><br/>', '', stripslashes($field['desc']);

                    break;

            }

            echo    '<td>',

                '</tr>';

        }



        echo '</table>';

    }  



    // Save data from meta box

    add_action('save_post', 'codituts_slidelink_2_save');

    function codituts_slidelink_2_save($post_id) {

        global $post;

        global $slidelink_2_metabox;



        // verify nonce

        if (!wp_verify_nonce($_POST['codituts_slidelink_2_meta_box_nonce'], basename(__FILE__))) {

            return $post_id;

        }



        // check autosave

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {

            return $post_id;

        }



        // check permissions

        if ('page' == $_POST['post_type']) {

            if (!current_user_can('edit_page', $post_id)) {

                return $post_id;

            }

        } elseif (!current_user_can('edit_post', $post_id)) {

            return $post_id;

        }



        foreach ($slidelink_2_metabox['fields'] as $field) {



            $old = get_post_meta($post_id, $field['id'], true);

            $new = $_POST[$field['id']];



            if ($new && $new != $old) {

                if($field['type'] == 'date') {

                    $new = codituts_format_date($new);

                    update_post_meta($post_id, $field['id'], $new);

                } else {

                    if(is_string($new)) {

                        $new = $new;

                    }

                    update_post_meta($post_id, $field['id'], $new);





                }

            } elseif ('' == $new && $old) {

                delete_post_meta($post_id, $field['id'], $old);

            }

        }

    }

Phew. That is over. Come to your Dashboard and also you will find a brand new brilliant ‘Slides’ Custom Post Type.

add_new_slide

Step 3 Load Slider Files

Turn on slider.php . Right now we’re going to en queue j Query, the Flex Slider j Query script or the Flex Slider style sheet. Or simply you can copy the code from flexslider.css to your style.css file folder in case desired.

 <?php



// Enqueue Flexslider Files



    function codituts_slider_scripts() {

        wp_enqueue_script( 'jquery' );



        wp_enqueue_style( 'flex-style', get_template_directory_uri() . '/inc/slider/css/flexslider.css' );



        wp_enqueue_script( 'flex-script', get_template_directory_uri() .  '/inc/slider/js/jquery.flexslider-min.js', array( 'jquery' ), false, true );

    }

    add_action( 'wp_enqueue_scripts', 'codituts_slider_scripts' );

When we’re doing so, there’s some thing you must actually do. Due to our file folder structure, the flexslider.css requirements a few changing so that it knows where can you find the arrow picture. Open up it up or try a search and also exchange for:

  • pictures with. ./images

Step 4 Initialize Slider

Right now you need to insert a few jQuery to our <head> in order to initialize the slider. Let’s add the following collections to slider.php below the code we just simply inserted!

// Initialize Slider



    function codituts_slider_initialize() { ?>

        <script type="text/javascript" charset="utf-8">

            jQuery(window).load(function() {

                jQuery('.flexslider').flexslider({

                    animation: "fade",

                    direction: "horizontal",

                    slideshowSpeed: 7000,

                    animationSpeed: 600

                });

            });

        </script>

    <?php }

    add_action( 'wp_head', 'codituts_slider_initialize' );

One reason I decided to using FlexSlider is really because of it is flexability. There are also quite a lot of guidelines you can actually mess with, but then I simply just providedfour very important ones above. Try out changing slide to fade, or even horizontally to vertically. You can make a look and feel at most of the paremeters over right here.

Notice: Make sure that a different way to do the above is using the wp_localize_script function ( view in Codex ) but yet this a little bit of bit in advance for this rule tutorial. However, Pippin Williamson ( a different codituts+ author ) have simply just written an outstanding article on this subject at the time you’re interested in you.

Step 5 Create Slider

Right now we’re going to basically set up the website template for the slider. 1st, we’ll do a WP_Query to pull ‘posts’ from the Slides Custom Post Type. Next, we’ll check out slides and if so that start up the slider. We’ll and then start up the loop. Each and every ‘slide’ will be able to check out in case a slide Link has become set up if at all so that, set up a web link for this. The slide’s picture will be able to be shown or the loop can be already closed up.

// Create Slider



    function codituts_slider_template() {



        // Query Arguments

        $args = array(

            'post_type' => 'slides',

            'posts_per_page' => 5

        ); 



        // The Query

        $the_query = new WP_Query( $args );



        // Check if the Query returns any posts

        if ( $the_query->have_posts() ) {



            // Start the Slider ?>

            <div class="flexslider">

                <ul class="slides">



                    <?php

                    // The Loop

                    while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

                        <li>



                        <?php // Check if there's a Slide URL given and if so let's a link to it

                        if ( get_post_meta( get_the_id(), 'codituts_slideurl', true) != '' ) { ?>

                            <a href="<?php echo esc_url( get_post_meta( get_the_id(), 'codituts_slideurl', true) ); ?>">

                        <?php }



                        // The Slide's Image

                        echo the_post_thumbnail();



                        // Close off the Slide's Link if there is one

                        if ( get_post_meta( get_the_id(), 'codituts_slideurl', true) != '' ) { ?>

                            </a>

                        <?php } ?>



                        </li>

                    <?php endwhile; ?>



                </ul><!-- .slides -->

            </div><!-- .flexslider -->



        <?php }



        // Reset Post Data

        wp_reset_postdata();

    }

Step 6 Using the Slider

Well, we’ve finally made the slider! Now it’s time to actually use it. You can open up any template file, such as index.php, and echo the codituts_slider_template function to display the slider.

So if we wanted to show the slider in Twenty Eleven right after the header on the home page, we would open up index.php and just beneath get_header( ); ?>, add the following:

1              <?php echo codituts_slider_template(); ?>

But what if you’re making this for a client or someone who just doesn’t want to touch template files and PHP? We should probably create a shortcode for them, so they can just use the slider with a [slider] shortcode.

Insert this at the bottom part of slider.php:

// Slider Shortcode



    function codituts_slider_shortcode() {

        ob_start();

        codituts_slider_template();

        $slider = ob_get_clean();

        return $slider;

    }

    add_shortcode( 'slider', 'codituts_slider_shortcode' );

The slider is now able to used within posts, pages and anywhere else in the home that will accept a shortcode!

slider

Download

When you’d just like, you can easily download the slider file folder that contains everything we experienced on this article. You simply need to drop it in your theme’s Inc file folder (and anywhere else is great, but yet makes sure you modify the code below) and then insert the following to the functions.php:

// Create Slider Post Type
require( get_template_directory() . '/inc/slider/slider_post_type.php' );
// Create Slider
require( get_template_directory() . '/inc/slider/slider.php' );

Notice: For the benefit on this article, the namespace/text domain name codituts have been used. You can actually do searching and also exchange on almost all code when you’re simply just copying/pasting it and also exchange:

  • codituts_ with yourname_
  • ‘codituts’ with ‘yourname’

Submit a comment

Pin It on Pinterest