Create a FlexSlider Gallery Using Attachment Images in WordPress without a Plugin

Posted on April 22nd, 2014 in Tutorials

Have you ever wanted to automatically pull multiple image attachments from a WordPress posting and present them as a Flexslider gallery without needing to insert short-code or use a plugin? Yes? Then this tutorial is for you!

The Challenge

For some time now, I have been a fan of using Flexslider by WooThemes as an image gallery in my websites. I have even written up an exercise on how to implement it into a static site for my Human-Centered Design & Engineering students at the University of Washington.

See Also: Create an Image Slider with jQuery | HCDE598 | Premium Design Works

But, since I don’t really run any static sites any longer, I had to figure out how to integrate it into my WordPress sites.

In the past, I had used various gallery plugins that used shortcode:

Using Shortcode

Using Shortcode

The issue with this was that I had to write said shortcode and it’s attributes into each posting which is relatively inefficient. Basically, I did not want have to copy and paste shortcode from one posting to the next any longer.

See Also: Shortcode API | WordPress Codex

Instead, what I wanted was to have a gallery automatically render the images that I uploaded to each of the postings without any hassle. I also knew that I wanted this gallery to display at the top of all my postings.

Since I was already armed with Flexslider by WooThemes, the question then became, “How do I integrate this without using a plugin?”

Integrating Flexslider by itself is relatively easy.

First, you need to download the package and put the files in the necessary place:

Necessary FlexSlider Files

Necessary FlexSlider Files

Once you have downloaded the package and placed the files in the correct place, you will need to hook the files up.

First, link to the stylesheet in your header.php file:

<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/flexslider.css" type="text/css" media="all" />

Second, link to the JavaScript in your header.php file:

<script src="<?php bloginfo('template_directory'); ?>/scripts/jquery.flexslider.js"></script>

Note: Don’t forget to link to the jQuery Library first!

Lastly, hook it up with the JQuery function in your header.php file:

<script type="text/javascript">
    $(window).load(function(){
        $('.flexslider').flexslider();
    })
</script>

But, when it comes to pulling the images from a posting without using a plugin is where the challenge was for me.

The Solution

This is where I needed to figure out a way to pull the images from a WordPress posting and write them into the markup that FlexSlider required.

The function that I wrote was, to me, both elegant and simple.

You can see this function in my functions.php file:

<?php

function add_flexslider() { // display attachment images as a flexslider gallery on single posting
     
    global $post; // don't forget to make this a global variable inside your function
    
    $attachments = get_children(array('post_parent' => $post->ID, 'order' => 'ASC', 'orderby' => 'menu_order', 'post_type' => 'attachment', 'post_mime_type' => 'image', ));
    
    if ($attachments) { // if there are images attached to posting, start the flexslider markup
        
        echo '<div class="flexslider">';
        echo '<ul class="slides">';
    
        foreach ( $attachments as $attachment_id => $attachment ) { // create the list items for images with captions
        
            echo '<li>';
            echo wp_get_attachment_image($attachment_id, 'large');
            echo '<p>';
            echo get_post_field('post_excerpt', $attachment->ID);
            echo '</p>';
            echo '</li>';
            
        }
    
        echo '</ul>';
        echo '</div>';
        
    } // end see if images
    
} // end add flexslider

?>

This is where I first needed to pull the array of data from WordPress using the get_children() function that can retrieve the attachments to a posting. I then needed to re-key the array to set my parameters of the gallery and declare it as the $attachments variable.

From there, it was a matter of writing a conditional statement to see if there were images attached to the posting. If there were, write the FlexSlider markup and use a foreach loop to call both the image using the wp_get_attachment_image() function and it’s caption using the get_post_field() function.

Once that function was written, I just needed to place the call to it within my single.php file:

 <?php add_flexslider(); ?>

Now, every time I create a new posting and add images to it, it will automatically display as a FlexSlider gallery!

Mike Sinkula has a B.A. in Communication Design from California State University, Chico, an M.S. in Human Centered Design & Engineering from the University of Washington and teaches web design at Seattle Central Community College and the University of Washington.

25 Comments:

  1. Adam says:

    Hi Mike,

    I have used your code exactly and I cannot to get it to work—I suspect, perhaps, because the images I am trying to pull are inserted from hyperlinks. Please see my full question on wordpress.org for more details:

    http://wordpress.org/support/topic/pull-all-postpage-images-for-slider?replies=1

    Would you be willing to help a brother out? Many thanks in advance!

  2. Hossein Rad says:

    Hi
    Thank you very much to share this.

    I need this slider with thumbnails and nav.

    http://flexslider.woothemes.com/thumbnail-controlnav.html

    Please add this in this tutorial.

  3. Mihai says:

    For slider with thumbnails use this JS:

    // PHOTO GALLERY PAGE SLIDER CAROUSEL
    jQuery(window).load(function() {
      jQuery('#page-carousel').flexslider({
        animation: "slide",
        controlNav: false,
        directionNav: false,
        animationLoop: false,
        slideshow: false,
        itemWidth: 70,
        itemMargin: 5,
        asNavFor: '#page-gallery'
      });
      jQuery('#page-gallery').flexslider({
        animation: "slide",
        controlNav: false,
        animationLoop: false,
        slideshow: false,
        sync: "#page-carousel"
      });
    });
    // END OF PHOTO GALLERY PAGE SLIDER CAROUSEL

    And for function.php use this code:

    // CUSTOM GALLERY WITH FLEXSLIDER
    function add_flexslider() { // display attachment images as a flexslider gallery on single posting
        $attachments = get_children(array('post_parent' => get_the_ID(), 'order' => 'ASC', 'orderby' => 'menu_order', 'post_type' => 'attachment', 'post_mime_type' => 'image','caption' => $attachment->post_excerpt, ));
        if ($attachments) { // if there are images attached to posting, start the flexslider markup        
            echo '';
            echo '';
            foreach ( $attachments as $attachment_id => $attachment ) { // create the list items for images with captions 
                echo '';
                echo wp_get_attachment_image($attachment_id, 'large');
                echo '';
                echo get_post_field('post_excerpt', $attachment->ID);
                echo '';
                echo '';     
            }
            echo '';
            echo '';
    
            echo '';
            echo '';
            foreach ( $attachments as $attachment_id => $attachment ) { // create the list items for images with captions 
                echo '';
                echo wp_get_attachment_image($attachment_id, 'thumbnail');
                echo '';
                echo get_post_field('post_excerpt', $attachment->ID);
                echo '';
                echo '';     
            }
            echo '';
            echo '';  
        } // end see if images
    } // end add flexslider

    Hope it helps!

  4. Dave Kelsen says:

    Exactly what I’m looking for, but images aren’t loading. Does the code for functions.php need to be changed for a custom post type?
    Thank you!

  5. Rafal says:

    There is a problem. the $attachment var gives:
    – Undefined variable
    – Trying to get property of non-object
    just in thi line:

    $attachments = get_children(array('post_parent' => get_the_ID(), 'order' => 'ASC', 'orderby' => 'menu_order', 'post_type' => 'attachment', 'post_mime_type' => 'image','caption' => $attachment->post_excerpt, ));
    • Rafal says:

      Ah ok… the problem is that you are trying to ghet the caption from a var that you are just asigning value to so in the time of doing it it’s empty.

    • Mike Sinkula says:

      You are actually right. You don’t need

      'caption' => $attachment->post_excerpt

      So, it’s been removed from the tutorial.

  6. Xawil says:

    Hi, I love this function. thanks for sharing. The only thing I couldn’t find is a way to add a link to a large version of the image when you click over them.
    Can you help me with it?

  7. hi there, im almost there, but the images wont show – they have loaded in the source code but something is preventing the jquery showing them again

    please help – see link,
    regards craig

  8. Xawil says:

    Damn it!
    I have a new problem here.
    In standard post. this function worked very well.
    But… I decided to create a custom post type because I am manipulating products, so I created a custom post type called “product” and the function didn’t work anymore.

    Any suggestion?

  9. ziga says:

    im having a problem, the code is working some how but its calling an image in media folder not the image attachment field from the custom post type, any idea ?

  10. Claudio says:

    Sosterà, I’m not so expert in wordpress and php so what do you mean for script folder and root folder?
    Thank you

    • Gordan says:

      Root folder is the root folder of WordPress, where wp-config.php file is located. Scripts folder you can create by yourself or maybe it is already there, and it is usually located at “\wp-content\themes\[Your-Theme-Name]\scripts”.

      • Gordan says:

        Sorry Claudio, Mike just corrected me, in this case, the ‘root folder’ is actually the Theme’s folder. For instance \wp-content\themes\[Your-Theme-Name].

  11. Gordan says:

    Hello, please help, the images are showing in my source code but not on the front end. Exaclty as @craig simpson’s issue above. What is causing this?

    • Gordan says:

      If anyone else has this problem I found a workaround:

      In my Chrome Inspector, under Console Tab, it output 2 errors:
      1) Uncaught ReferenceError: jQuery is not defined
      2) Uncaught TypeError: $ is not a function

      The 1st error is fixed by placing the script AFTER any wp_head(); calls. This makes sure no conflicts with previous jQuery calls.

      The 2nd error is fixed by using the JQuery’s ‘noConflict’ mode, because the string ($) is laready “taken”, so to speak:


      var jq = jQuery.noConflict(); // I declared "jq" instead of "$"

      and then replace “$” further in the code:


      jq(window).load(function(){
      jq('.flexslider').flexslider({
      animation: "fade",
      slideshow: false,
      });
      })

      Mike, I would like to know is it safe to leave the code like this in WordPress environment? I wouldn’t want to leave it like his if it will create new complications further along (if it is a hack, and not a clean solution).

  12. Rana says:

    HI,

    very nice code for gallery. I have problem with this code it grabs all the images for slider. I would like to control what image should be in slider and what should not be. How can i achieve this? I have slider and I have a product picture I don’t want to add this product picture into slider.

    I will appreciate your help.

    thanks in advance

  13. When inserted, the needles keep in place for several minutes, which
    normally does not lead to substantially pain.

  14. Chris says:

    Sorry, silly question where do you put the js code for the slide with nav?

    Save as file name / type? In scripts folder?

    Sorry bit of a noob.

    Many thanks.

  15. Chris says:

    Its cool I found where, not working but I found it lol

Leave a Comment:

Don't forget to get your Globally Recognized Avatar.