Creating a sticky post slider

Brief background

Creating a slider is simple. For some. In WordPress there are a lot of ways to creating a post slider, image slider, category slider and just about any type of slider you could possibly imagine. The one I wanted to share is creating one with sticky posts. You know the ones that you have to pick from the slightly hidden options.

Make post sticky

Yeah. That little guy. The way WordPress handles sticky post is by putting them on the front page and keeping them on top regardless of when it was posted. A good example is the quick image I created to help illustrate.

The requirements

WordPress has plenty functions and plenty of ways of getting the required posts. One way of getting posts is using get_posts() but that isn’t the method I’ll be using. I’ll be using the WP_Query and alter it just a little bit. No, not with query_posts because that will just cause the world to implode. Okay, not really but there are several other reasons not to use that function.

The steps

In order to have a good functional featured post slider we first need to layout the steps needed. What I did initially was make a quick list of the steps.

  1. Get the posts
  2. Check if there are any ‘sticky’ posts
  3. If there are then run our code
  4. Ignore sticky posts in regular feed
  5. Drink up

The code

Now that we have our logic we can get started.

The first thing we have to do is get all the posts that are set to be sticky. We create and array to hold these.

$stickies = get_option( 'sticky_posts' );

We need to count how many posts there are and we’ll store that as a variable so we can use it later on.

$count = count( $stickies );

Now that we have an array and the total we can start a new query for only those posts. The way we do this is by creating a new WP_Query and passing some arguments. So we’ll create these arguments and name our newly created object of posts $featured. It can be whatever you want it to be. If you are submitting to the WordPress repo then prefix it with your theme or equivalent.

$args = array(
	'post__in'       => $stickies,
	'posts_per_page' => 3,
	'post_type'      => 'post',
	'nopaging'       => true
$featured = new WP_Query( $args );

Now that we have our new object filled with posts we can run our code with the newly created query. But wait! When WordPress is first installed there are no sticky posts so then how do we check for that? Simple. Remember that we stored the value into a variable called $count? We’ll use that. We’ll use an if statement to run our code. If there are no posts then we’ll begin the newly created WordPress loop.

if ( $count > 0 ) {
  // run WordPress loop using $featured

Sounds simple now that we have it all together, right? Now we can create the loop and fill it with all the goodies and information we want using template tags. Don’t forget to use wp_reset_postdata() to reset our post data. There is one last thing we must do to get it all working right and that is hooking to pre_get_posts.


One more thing?

Yes, one last thing. I know a bit of a curveball but this is what will prevent the doubling of sticky posts. What we have to do is add just a few lines of code to our functions file of our theme.

add_action( 'pre_get_posts', 'my_awesome_theme_pre_posts' );
function my_awesome_theme_pre_posts( $query ){
    if ( is_home() ){
        $query->set( 'post__not_in', get_option( 'sticky_posts' ) );

    return $query;

Now that we have that done we have our final code snippet:

// Create array of all the sticky_posts
$stickies = get_option( 'sticky_posts' );

// Count how many there are, if any
$count = count( $stickies );

// Create a set of arguments to pass
$args = array(
	'post__in'       => $stickies,
	'posts_per_page' => 3,
	'post_type'      => 'post',
	'nopaging'       => true

$featured = new WP_Query( $args );

// If there is one or more sticky post we create our new slider
if ( $count > 0 ) : ?>
<section class="featured" id="featured-slider">
    <?php while( $featured->have_posts() ) : $featured->the_post(); ?>
    <article <?php post_class( 'featured' ); ?> id="post-< ?php the_ID(); ?>">
        <h1 class="featured-title"><?php the_title(); ?></h1>
        <div class="content"><?php the_content(); ?></div>
        <div class="content"><?php wp_link_pages(); ?></div>
        <footer class="meta">Posted: <?php the_time( get_option( 'date_format' ) ); ?></footer>
    <?php endwhile; wp_reset_postdata(); ?>
</section><!-- end of our featured article slider -->
<?php endif; // end the featured posts ?>


And done! For the most part since we need to add interaction but I’ll let you pick out what to use since there are plenty of jQuery slider plugins to help with that.

Issues with my_query

Recently I was in the middle of creating a theme that had support for a front page and blog with featured posts that displayed in a certain manner. I read up on how to create a new WP_Query and felt pretty confident I would be able to get the desired results. Yeah, I was a little wrong. I got results but what ended up happening was that some of the posts were being place in the wrong sequence.

I got frustrated and had to take some time away from it. I turned to my source of inspiration and motivation: theme reviews. One of the themes that I reviewed used a method that I wanted. I looked at how they coded it and as it turns out it was the way I thought. New WP_Query object and



I tried using the code and wondered what would happen if there were no sticky posts. I thought about this only because by default WordPress only creates one post and there are no sticky posts. What did it return? It for some reason returned all posts. The code was fairly simple:

$args = array(
        'posts_per_page' => 10,
        'post_status' => 'publish',
        'post__in' => get_option('sticky_posts')
$fPosts = new WP_Query( $args );
$countPosts = $fPosts->found_posts;

if ( $countPosts > 1 ) { // run code for slider }

The downside to this is that


is not the amount of sticky posts. It kept driving my crazy when I had no sticky posts because it would return all posts. I was about ready to punch a wall. Such a simple thing and I couldn’t figure it out.

I read the WordPress docs about the WP_Query and noticed that the function

get_option( 'sticky_posts' )

creates an array of posts. That’s when the light bulb turned on and I altered the code.

Archive widget at a glance

Today I put the finishing touches to my customized archives widget. While I am tempted to submit it to the WordPress plugin repository I will hold off for a little bit. The reason: I’m not quite ready. That will usually be my excuse.

Enough of that on to the code!

The issue

I love using archives only because I love some aspects of history. The one problem I had with the way the core widget handles it is that it shows every single month with no set limit. I wanted to be able to set a limit without having to use code or a child theme to modify the widgetized areas.

The steps

In order to create a simple plugin one of the first things I had to do was look at the core default widgets. That file is found under


and houses all the basic widgets that come standard with WordPress. Next, I created a blank folder with a blank PHP file with the name of my new plugin; used the standard header for a plugin and input all my information:

Plugin Name: Lost Archives
Plugin URI:
Description: Custom Archive Widget with a few extra options.
Version: 0.1
Author: Jose Castaneda
Author URI:
License: public domain


The next thing was to get the basic logic behind what I wanted my newly created widget to do. What information I wanted to gather from a user and what to pass so that it will display properly on the front end. The basic one being the title of the widget. Next I wanted the ability to pass a number so that it sets the limit to how many things to show. Finally I wanted the ability to to chose what type of archive to display; if I wanted a weekly, daily, or monthly type of archive.

The code

In order to gather the information I first needed a form. Thankfully WordPress makes things pretty easy with the widget class. By creating a new class that extends the WP_Widget class I can override the

function form(){}

and use it to create the form the user sees on the back-end. This was a little tricky in that I had to run a check for what is currently selected and what isn’t; and, again, WordPress has a function for this:

selected( $selected, $current, $echo)

In order to display the different options I had to use a foreach() loop in order to display the various choices. The code looked a little like:

foreach( $array as $key => $value ){
    echo $key;

Now I know I could have cleaned things up a little bit but that is for another time and another post.

The end result

And the final product is:

Plugin Name: Lost Archives
Plugin URI:
Description: Custom Archive Widget with a few extra options.
Version: 0.1
Author: Jose Castaneda
Author URI:
License: public domain


add_action( 'widgets_init', 'lost_archive_widget' );
function lost_archive_widget(){
    register_widget( 'lost_archives' );

class lost_archives extends WP_Widget {
    function __construct() {
        $widget_ops = array(
            'classname'   => 'archives_extended',
            'description' => esc_html__( 'Customized Archives wigdet.', 'text-domain' )
        parent::__construct( 'solea_archives_widget', esc_html__( 'Archives', 'text-domain' ), $widget_ops );

    function widget( $args, $instance ){
        extract( $args );
        $limit = ( empty( $instance['limit'] ) ) ? '12' : $instance['limit'];
        $type  = ( empty( $instance['type'] ) ) ? 'monthly' : $instance['type'];
        $title = apply_filters('widget_title', empty($instance['title']) ? __( 'Archives' ) : $instance['title'], $instance, $this->id_base);

        $content = wp_get_archives( array(
            'type'            => $type,
            'limit'           => $limit,
            'format'          => 'html',
            'before'          => '',
            'after'           => '',
            'show_post_count' => false,
            'echo'            => 0,
            'order'           => 'DESC'
            ) );

        $output = '%1$s %2$s %3$s %4$s <ul>%5$s</ul> %6$s';
        printf($output, $before_widget, $before_title, $title, $after_title, $content, $after_widget );

    function update( $new_instance, $old_instance ){
        $instance = $old_instance;
        $new_instance = wp_parse_args( (array) $new_instance, array( 'title' => '', 'type' => '', 'limit' => '') );
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['limit'] = $new_instance['limit'];
        $instance['type'] = $new_instance['type'];
        return $instance;

    function form( $instance ){
        $instance = wp_parse_args( (array)$instance, array( 'title', 'limit', 'type' ) );
        $title    = strip_tags($instance['title']);
        $limit    = $instance['limit'];
        $type     = $instance['type'];
        $types    = array(
            esc_html__( 'Post', 'text-domain' )    => 'postbypost',
            esc_html__( 'Daily', 'text-domain' )   => 'daily',
            esc_html__( 'Weekly', 'text-domain' )  => 'weekly',
            esc_html__( 'Monthly', 'text-domain' ) => 'monthly'
        ); ?>
        <label for="<?php echo $this->get_field_id('title'); ?>">< ?php _e('Title:'); ?></label>
        <input id="<?php echo $this->get_field_id('title'); ?>" class="widefat" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="< ?php echo esc_attr($title); ?>" />
        <label for="<?php echo $this->get_field_id('limit'); ?>">Limit:</label>
        <input id="<?php echo $this->get_field_id('limit'); ?>" class="widefat" name="<?php echo $this->get_field_name('limit'); ?>" type="text" value="< ?php echo esc_attr($limit); ?>" />
        <label for="<?php echo $this->get_field_id('type'); ?>">Type:</label>
        <select id="<?php echo $this->get_field_id('type'); ?>" name="<?php echo $this->get_field_name('type'); ?>">
        <?php foreach( $types as $k => $t ){
        echo '<option selected="selected" value="' . $t . '">'. $k . '</option>';
        } ?>


Keeping in mind this works with WordPress 3.5 and above and I haven’t tested any other versions.

Displaying the gallery count and the images

Sometime last week I had an idea that finally managed to come alive. More and more I have been getting more and more ideas when it comes to creating WordPress themes. The most recent one being a theme that – much like twenty-thirteen does – showcases post formats. I still have to work with audio, video as well as a few other formats but the one that really had me in a bit of a pickle was the image gallery.

When WordPress 3.5 was released it introduced a better method of media insertion. Extremely user-friendly. I fell in love with it when I saw the mock-ups in the blog. One thing that really intrigued me was the use of multiple galleries in a single post. I thought: this should make for great use of the Content Management System side of WordPress.

The Idea

My next thought was how to harness that and be able to display it for those that would like to know. Being a photographer by hobby I wondered how to get that information. The first thing was to count instances of a single gallery. The next would count the images in all the galleries. Simple. By first getting the gallery instance count I could now set a simple if/else statement for my output.

The code

Looking at some example galleries gave me some clue as to what to look for. The next step was to gather the needed information. Thankfully WordPress has some really simple, and neat, functions to help and make things a little easier. The one function that actually does most of the work is get_posts() by getting all the attachments in a given post. From there you can find how many instances a post has a simple regular expression matching magic.

So the first thing is to count how many images there are in the post. Now, we can use get_children but the thing I found interesting about that function is that it calls get_posts. I figured cut the middleman and just use get_posts instead. So my gallery page looks a little like:

// Get all the attachments
$attachments = get_posts ( array(
 'numberposts' => -1,
 'post_type' => 'attachment',
 'post_mime_type' => 'image',
 'post_parent' => get_the_ID(),
 'post_status' => 'inherit',
 ) );

// Count all the attachments
$total = count( $attachments );

Now, I know it may seem a little strange for some as to why I’m getting the post_type of ‘attachment’ but that is how WordPress handles media and posts in general from what I’ve learned. Next thing is to get the gallery shortcode.


Yes, I said shortcode. WordPress uses shortcodes on a given post to display certain things and a media gallery is a good example of this. The plus side is that there is a function that grabs that for us. At least the regular expression for the shortcode. Next, we store it for later use and grab the content as well:

// Get the content in order to find the gallery shortcode
$string = get_the_content();

// Get the gallery shortcode regex
$pattern = get_shortcode_regex();

With that we can now use PHP regular expression matching and match all the instances of [gallery] in a single post and store it for later use. With two PHP functions we now have the end result:

// Get all the attachments
$attachments = get_posts ( array(
    'numberposts'    => -1,
    'post_type'      => 'attachment',
    'post_mime_type' => 'image',
    'post_parent'    => get_the_ID(),
    'post_status'    => 'inherit',
    ) );

// Count all the attachments
$total = count( $attachments );

// Grab the permalink
$link = get_permalink();

// Get the content in order to find the gallery shortcode
$string = get_the_content();

// Get the gallery shortcode regex
$pattern = get_shortcode_regex();
preg_match_all( "/$pattern/s", $string, $matches );

// Count how many matches and store it for later use
$galleries = count( $matches[0] );

// IF there is only one gallery show just the image count else show both the gallery and image count
if ( $galleries > 1 ):
    $output = 'With <span class="gallery-count">%2$s</span> galleries with <span class="image-count">%1$s</span> images unique images.';
    $output = 'With <span class="image-count">%1$s</span> unique images.';

printf ( $output, $total, $galleries );

The result

The end result that I wanted was a simple line of text that provides simple information for a visitor. The one thing to note though is that if galleries share a photo it will not be counted twice.

Regular Expressions and I

The last two days have been a little weird for me since I’ve had this idea on how I want my image galleries to look like in the front page and I have yet to find the right solution.

I’ve had to resort to using what I’ve never really tried exploring just yet: Regular Expressions. Almost a year ago I tried to learn but got sidetracked with random other things like I usually do. This time I’m fully alert and ready to tackle this little task for a simple thing like finding numbers within a simple string.

The reason I’m having to resort to using regex is because for some reason I can’t seem to get a count for all the attachments from a single post that uses multiple galleries. It for some strange reason wants to only get the first galleries’ images and not the rest. It’s been driving me insane to an extent.

What I’m wanting to achieve sounds simple enough but for some reason it keeps giving me a headache that seems to not want to end.

The way the gallery will look sounds simple enough because all I want to display in the main/home/index page is one or two things. The first one being text that says how many galleries there are if there is more than one gallery being used in the post and how many images there are in the entire post. The second being a thumbnail of one image if there is only one gallery in the post.

The next stage is getting the styling for the gallery when it’s being viewed. Thankfully I am understanding what file is being queried thanks to the ‘debug’ plugin and the flowchart that I often try to use when I’m wanting to figure out what file to use. The file that will be next in my line up will be the attachment file. I’ve seen some good examples; they all seem to follow a common pattern which is good because I’ll be able to use a simple design.

In the meantime I still need to figure out how I’m going to count all the images in a single post that uses more than one gallery.

Looks like I’ll be reading and spending more time in front of a screen to solve my little dilemma.

Learning with practice

The progress of my theme is decent. I have been learning how to work with Git and SVN more and more. I did recently have a little conversation with @ipstenu on Twitter about learning version control. Yes, I am still learning how to harness the power of simple commits and getting the hang of how to use branches and tags.

Which brought me to my main point: tutorials.

People on the web have dozens and dozens of them. Some are better than others and some are just beyond outdated. I was looking for a tutorial on how version control works using SVN. You would think I would find at least five. No. I found links talking about how SVN works but no real tutorial.

@ipstenu asked me if I could find one noob friendly tutorial. Of course I couldn’t. True, there wasn’t one. Yet. I have been contemplating creating a simple tutorial on how to use TortoiseSVN in a local setup. Sounds simple, right? Yes and no. The writing is a simple thing but taking all those screenshots to go with that will be a task in itself. I know I’m capable of it I just now have to find the time. Keeping in mind that even my current knowledge is not that great but it should suffice for the time being.

One of the first things that I learned was ‘commit’ so of course that will be the first topic. Next in line is ‘branches’ and ‘tags. and how they work. That is one thing I still haven’t yet mastered through a GUI. Just takes me back to when I was in Junior High and learning about computers but that is another story.

Yes, tutorials have helped me understand certain things but often times I don’t really learn unless I put forth the effort. Learning by practice is a great method and a great way for me and others to learn as well. I just hope that I can get my tutorial written out so that people understand. Although this has given me an idea for a future post: translation.

HTML validation issues

If it’s one thing I hate it’s loading up a site, click on something and then the layout gets all wonky on me. For the last two years I have read and learned about HTML and CSS validation. The one thing I have learned is that there are people out there that don’t care for it.

What I have learned from reading tutorials, forums and glanced from other (what I consider professionals) developers is that validation is key. I, too, agree that it should be good practice. Better yet: natural. The one issue I have run into as of lately is that WordPress will output an empty element and you get an error in validation. The other thing I noticed is that often times an image doesn’t always get a “alt” attribute. Yes, this can be remedied by making one in the media editing section but what happens when a user doesn’t put one in?

I think that by default WordPress should at least create a sort of container or filler for those rare scenarios. A good example is the gallery shortcode and the captions it creates; or rather it doesn’t. When there is no caption for the image it will still output that element but will be empty. Bad. Rather than creating an empty element just don’t output it. Again: bad.

So, rather than nothing do something. It’s what I kind of did with a quick solution.

$caption = wptexturize( $image->post_excerpt );
 if ( !empty($caption) ) {
 $output .= "tt< {$captiontag} class='wp-caption-text gallery-caption'>" . $caption . "n";
 } else {
 $caption = "No caption entered";
 $output .= "tt< {$captiontag} class='no-caption'>" . $caption . "n";

It works for my needs and what is really nice is that if I forget to put a caption on an image for my gallery posts it will say: No caption entered.

Now I just have to work on REGEX to remove unwanted attributes. The journey continues! 🙂

One more week

Earlier today when I got home from work I did my usual routine of updating to the most current development version of WordPress, made sure all other applications were up to date and opened up my code editor (Notepad++) to view and edit my theme files. Since I was wide awake I tried my hand at experimenting with Git and TortoiseGit on my main computer. One thing leads to another and I managed to delete my theme. I hadn’t made the last commit of adding my modified gallery shortcode.

Needless to say I am kicking myself pretty hard. What this means now is that I am starting over with a new repo but still with SVN and not Git. Git will be for my next project theme. The reason I am starting over is because I deleted the working copy and didn’t realize that I hadn’t added all the files and hadn’t made all the commits I needed to be in sync.

In about one week WordPress 3.5 will be launching and I am pretty stoked about it. The reason is because the way media is uploaded has improved. I feel this is a huge step in the right direction for WordPress development and adoption. People want to be able to share not only their stories but some want to share photos, videos and sometimes audio. The uploader is fairly easy to use and the user interface is elegantly designed.

But enough drooling about what is to come more about what I was trying to get across: patience. I have plenty of it and sometimes I feel I have too much of it. In one week I will make an attempt to rebuild all the code I lost and have it all finished by the time 3.5 launches. This should be manageable since I know what files I need this time after having tested file hierarchy with my previously deleted theme.

Today I created all the empty files and committed that to the repository so I can code away and make the final commits when I am satisfied with the code; that way I won’t have so many commits and a lot versions to go through down the line if I ever have to see why I did what I did.

Me, WordPress and Template tags

Recently I have been working more diligently on putting some finishing touches on my personal blog’s theme. Working on a local machine is so much easier now that I understand how it works. I remember when I started out with PHP it was painful.

I got frustrated because I didn’t know where the files had to go at first, the changes I had made to the configuration weren’t taking effect and random little things that almost discouraged me from continuing.

The other day I was reading on the WordPress forums seeing if there was somebody I could help. One thing leads to another and I wind up looking at frameworks, plugins and template tags. Now, I have posted something pretty similar to this before because it was a bit of a rant when I saw somebody posting code I felt was not good practice but that is besides the point at the moment.

What I really want to get to is why I’m writing about template tags. They are an extremely useful thing to know – to some. WordPress has several template tags at your disposal and I love it. There are however some that I have seen in some themes that I would love to use in some of my themes down the road.

A perfect example is using a template tag for navigational links. WordPress has a really good template tag:

< ?php posts_nav_link(); ?>

Simple. It does the job: create navigational links for more posts. I feel the downside to that is that it is all in one container. Yes, there are ways around it by creating your own template tag (which a lot of people seem to do) and use that instead. But what to use? I like the Kubrick method of navigational links where rather than using the one


you use two in one. Creating a previous and next link is easy. A better way of doing this is if you are using just the bare minimum amount of files in a WordPress theme is using conditionals to create the navigational links for certain looks.

< ?php
/* Create page navigation and post navigation
 * depending on what is being viewed.
if ( is_single() ) { ?>
< ?php } else { ?>

< ?php } // end else statement

The little snippet works fairly decent but it is a little cluttered. It can be simplified a little more so that the only things that change are the


div>s containing the actual links. So we can modify it to:

< ?php
/* Create page navigation and post navigation
 * depending on what is being viewed.

Now we don't repeat code and saves some processing power for other things. Amazing what cutting down two lines of code will do! Now we can wrap all that into a function and use it as a template tag to make things easier in an


file. So the final code would look something like:

/* Create page navigation and post navigation
 * depending on what is being viewed.

function my_theme_nav_links() { ?>
< ?php }; // end my_theme_nav_links() 

Now we can use the function anywhere in our theme for post navigation.

Theme progress – good

Slowly but surely my blog’s is coming together. The one thing I am now attempting to do is work out a gallery system. While I do like the Twenty Twelve’s way of presenting the image gallery I want something a little different. The way the Twenty Twelve handles the images is by linking to a page. I don’t want that on mine. Part of that reason is because I won’t be having very many images that are bigger than 800 pixels wide.

What that really entails is that a person with a computer screen of about 13 inches will be seeing more photo than they bargained for. I don’t want to do that. Especially if a person is using a mobile device. That means that image would be the only thing that they see. That is a big no bueno for accessibility. Having to scroll side to side to view an entire image on a mobile device decreases the user experience in my book.

What I have so far is the single, comments, index, search form, sidebar, content, header, and footer pages completed. I still have to work on the functions, tweaks, custom template tags, page and post formats code pages. The one that I know will give my some issues will be the gallery.

I am slowly learning how to code that because the built-in gallery shortcode is not HTML valid. It outputs a element even when there is no caption for the image. What I have to do is one of two options: filter the gallery or remove the gallery shortcode and use my own. For the time being I think I will just have to settle for filtering the gallery output to get the desired result. Not that big of a deal; at least I’ll learn on the way.

The one thing I still have to finish, oddly enough, is the images that I will be using. I’m not sure if I will use individual files or just one since I do want to be able to support HiDPI down the road but that is another subject for another time. Right now I still have a few functions to declare and a few more things to code.