Make things a little more accessible

Key on keyboard
I was asked to redesign a site not too long ago and I’m pretty pumped about. Not going to lie. What I do like is that the site already has plenty of content to work with. The trick will be creating a good user experience for the person I will be handing off the site to.

The current state is blank since I’ve not really had much time to work. Personal matters. I do have a site design in mind but still need to sort out a few things here and there. I think the downside is that he wants the site to be finished as soon as possible. This may present a bit of an issue.

I can quickly get the ball rolling for him but the trick will be creating his theme and I may even have to experiment with a few plugin options to better enhance both his experience as well as user experience.

With that in mind when it comes to the actual coding of the site will be a feat as well. The reason is because I want to be that change. I want the web to excel and in a good direction. How will I achieve this? By making the site accessible. What do I mean by that? By using ARIA roles in my markup.

Yeah it does seem a little odd to be using those but it will all make sense. It’s just one step to creating a better web experience for everyone.

How will I use it?

The way I will go about this is by using


to make things a little more accessible. There are several roles in a document but they must be used properly. You can’t just go berserk and start giving everything a role just because you think it has to have one. In an HTML document there are some that really need them. HTML5 does play nicely with several of these.

The reason for wanting to use this is so people that aren’t able to view the site traditionally don’t miss out on certain things.

Let’s look at a decent example of this.


    Document Title


As you can see with HTML4 some of the information can seem a little repetitive. Now, when we change to HTML5 and use some ARIA roles it makes a little more sense.

< !doctype html>

    Document Title

As you can see the document makes a little more sense. You can tell what the role is of each element. I think that is one of the main reasons I have come to love using HTML5 markup. The ability to use elements like






, and


are a great addition and make for much easier organization of information.

The key will be reading the documentation for the roles and definitions of those roles. This will be fun!

Choosing the right path

It’s no secret that I love using WordPress and love design. Those are pretty obvious if you’ve known me for some time. I guess you could say I’m a little addicted to WordPress. My digital meth if you will, but I also love design about the same.

Working on WordPress themes is an amazing middle ground for me. It’s almost a zen state for me when I’m looking at a design and trying to figure out how to code the theme. Some themes require a little more TLC than others. A great example is when you have to think about the end user. As some may, or may not, know I like to help out in the support forums when I can.

I’ve even written a post about creating a child theme. Yes, I do encourage that in the forums as well if you want to make any modifications to any theme. The downside is that often times some themes don’t generally like to use: get_stylesheet_directory_uri()


Now, there are two things to remember when it comes to working with child themes.

  1. Use them
  2. Code properly for them

What I mean by number two is that you should be using the right function when it comes to enqueuing the stylesheets and scripts. In this case I’ll be talking about stylesheets.

A few days ago I was typing out some code for my theme and started to think about the structure of my folders. The most commonly used in themes seems to be to have all the CSS files bundled together and all the JavaScript files together as well. Simple and makes sense really. The downside is when some people use a stylesheet that resides in that folder. It does seem a little odd but it will all make sense in a bit.

The issue is when a parent theme uses the rule

@import url( 'path/to/stylesheet.css' );

in the main stylesheet. What that means is that the user now has to look for the location of the main stylesheet and create the right code for it. Or better yet have to include the

@import url( '../path/to/parent/stylesheet.css' );

rule in the child theme.

Why not make it a little easier for them?


By using a quick conditional check to see if the current theme is a parent theme or a child. Yes, there is a function for it. Believe or not it is actually:


Simple little function that checks to see if the stylesheet path and the template path are the same; if they are then it is a parent theme, otherwise it is a child. Quick and painless, right?

But how to use it to our advantage? Easy. When we register our scripts and styles we add on the little conditional and when it is a child theme we use both the child’s stylesheet as well as the one being used by the parent.

if ( is_child_theme() ){
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/css/mite.css' );
    wp_enqueue_style( 'child-style', get_stylesheet_uri() );
} else {
    wp_enqueue_style( 'parent-style', get_stylesheet_uri() );

You’ll notice that I am using two different functions when it is a child theme to enqueue the stylesheets being used.

The main reason for this is that when the function


is used it will get the location of the stylesheet of the active theme. We don’t always want that because if you are the a developer that likes to group their files accordingly then it may just lead to a little trouble.

With that little snippet you can now rest assured that when you activate the theme it will load the right path. Now in order for all of this to work we just add one minor thing to our style.css file:

@import url( ../css/theme-style.css );

Fairly straight forward, right?

Be friendly and filter your foot

HTML5 footer

A brief glimpse of my hosted blog’s footer. I’ve had that thing for nearly six years. Yep, six years. A little hard to believe that I only have about eighty posts but it’s true. Part of that reason being me branching off and trying on a self hosted site. I wish I could tell you all the things I’ve tried over the course of this branching but honestly don’t recall every little thing I’ve done.

I can honestly tell you I have learned a few things here and there from not only reading the WordPress codex  pages but from doing some theme reviews as well.

Be friendly

Yes, be friendly. What I mean by this is that you should think about who will be using your theme or plugin. True that not many people are capable of knowing how to code a site with PHP, HTML but that may not be your target, right? Odds are that you want to share your theme with the community.

That means that another developer will be looking at your code. Shock! Awe! You name the emotion, odds are that person will experience it at one point while looking at your code. The one you don’t want to bestow upon them is anger. Once that one hits their ability to trust you will dwindle.

How do you prevent it? Well, documenting is a great way. Another is by making things a little easier by adding hooks and filters to your theme.

Hooks and filters

Yes, hooks and filters. One simple solution to help everyone out. At least a good portion of people. You can’t really please everyone, unfortunately. One way of adding friendliness to your theme, or plugin, is by adding a simple action so that a child theme can easily hook to it. A quick sample would be just before the page of the theme.

< ?php do_action( 'page_prior' ); ?>

See? Simple, right? Then all a child theme, or even a plugin, has to do is hook to it. Now, that is a quick and painless way of making your theme a little easier to work with and a future developer will like it since they won’t have to change any files or create a separate file. But there is more! What’s even crazier to think about is that you can not only create minor changes that way but you can also make huge changes that way.

Suppose for a moment that you create a post structure that you feel would want to be changed down the road or by somebody else. Simple! You guessed it! Action hook. Now it is a little more work but you can do it with a few extra lines of code.

//somewhere in the index file
while ( have_posts() ) : the_post(); 
 do_action( 'theme_content' ); 

// in the functions file
add_action( 'theme_content', 'theme_content_cb' );
function theme_content_cb(){
    // inside the WordPress loop

Yeah it does look a little odd. But in the child theme’s function file all you would have to do is remove the action and add it again with your own callback function. So the child theme’s function would look a little like:

remove_action( 'theme_content', 'theme_content_cb' );
add_action( 'theme_content', 'child_theme_content' );
function child_theme_content(){
    // My child theme's content code

What is nice about that is you can easily alter an entire block of code without ever having to touch any parent theme files or having to create any duplicate files and modifying to your choosing. It is very convenient when you have to remove credits sometimes. One of the issues I see in the Themes and Templates forums.


Filtering the output is key in this. Why? Because it makes things just that much easier for the developer that will be using the theme. Remember to keep your audience in mind when creating a theme, or plugin. A good portion of the time it will be a developer. Adding a filter is as easy as using


and you’re done.

function theme_footer_cb( $theme_footer ){
    $theme_footer =
    echo apply_filters( 'theme_footer_cb', $theme_footer );

With that any themer can filter the output of the theme’s footer by adding a filter in the child theme’s function file like so:

add_filter( 'theme_footer_cb', 'child_theme_footer' );
function child_theme_footer( $footer ){
    $footer = '
Created with LUV
'; return $footer; }

Not so hard, right? Now go out and make a developer happy by creating these simple little hooks and filters.

Understanding arrays


For the last month I have read about JavaScript ( ECMAScript ) and how it works. To say the least I am one step closer to not being as bald as I thought I would be. JavaScript is a great language to learn and has so much potential behind it and for it.

What caught me a little off guard was the term object-oriented. For the longest time I hadn’t the slightest idea what that meant. I finally reached that pivotal moment when it hit me. That little moment of: that makes total sense.

What are arrays?

Arrays, simply put, are lists. Yes, it does sound sort of strange but it is true. Arrays are lists. In just about any programming language arrays are used to store not only information but information about that information. Yes, more information within information.

A great way of thinking what arrays are is to think of them as lists; which is kind of what they are. A good example is the little JavaSvript snippet:

var groceries = new Array( 'tomato', 'cucumber', 'squash', 'zucchini' );

Simple right? Now, what if we want to deal with and store more information? For that we introduce associative arrays.

Associative Arrays

Not the suit wearing type but the mathematical type. At least for me it makes sense. Not sure if it will help anybody else but here goes. An associative array is an array within an array.

Inception much?

A really great way to look at this is by not only looking at the code but thinking about lists. Yes, lists. Again. A great example of this is a restaurant’s menu.

$menu = array(
    'pizza' => array( 'cheese', 'pepperoni', 'sausage' ),
    'potato' => array( 'fried', 'baked', 'chopped', 'chip' ),
    'drink' => array(
        'soda' => array( 'diet', 'regular' ),
        'alcohol' => array( 'beer', 'wine' )
    'salad' => array( 'house', 'caesar' )

Wow! That is quite a bit of code to show my point but I will run through it pretty quickly.

We start with the basic menu items: pizza, potato, drink and salad. Each one of those items then has its own bit of information attached to it. Pizza has the toppings, potato shows how it is cooked, the drink one is a little tricky in that it has two different arrays for soda and alcohol.

Get it? Got it?

And there we have a small glimpse of how I am capable of understanding arrays and associative arrays. Very dumbed down but it is a very clear way of looking at it.

Creating a custom comment list


Comments. That is the topic. As some may know I’m in the middle of creating a WordPress theme to submit to the repository. I want this theme to not only pass but to pass with flying colors. I followed about as close to how the default themes are but have also integrated some from themes I have reviewed and added a bit of my own style, of course.

What started this?

What really initiated this was the default theme for WordPress 3.6: Twenty Thirteen. Previous default versions all passed a certain set of arguments and made a callback function in order to display the comments rather than have WordPress handle it. Wait? You mean to tell me that I can let WordPress do the coding for me? Yes. If you don’t like having control of how to structure your code. Twenty thirteen lets WordPress handle the coding of the comment list.


Yes, a callback function. Simple and you have more control of how the code is structured and displayed. The function that handles this is:


All that is needed now is some arguments:

$defaults = array(
    'walker'            => null,
    'max_depth'         => '',
    'style'             => 'ul',
    'callback'          => null,
    'end-callback'      => null,
    'type'              => 'all',
    'page'              => '',
    'per_page'          => '',
    'avatar_size'       => 32,
    'reverse_top_level' => null,
    'reverse_children'  => '',
    'format'            => 'xhtml', /* or html5 added in 3.6  */
    'short_ping'        => false, /* Added in 3.6 */
wp_list_comments ( $defaults );

Now, the thing that creates the comments is the callback. It tells WordPress to run the default code if no argument is passed. If there is one, then WordPress will look for that function and use that instead. In Twenty Twelve it was:

wp_list_comments( array(
    'callback' => 'twentytwelve_comment',
    'style' => 'ol'
     ) );

In the Twenty Thirteen theme it actually uses the default HTML5 markup by not setting a callback function and using the new argument:

'format' => 'html5'

This tells WordPress to use the HTML5 markup for the comment which is:

<article class="comment-body">
 <footer class="comment-meta">
 <div class="comment-author vcard"></div><!-- .comment-author -->
 <div class="comment-metadata">
 <a href="">
 <span class="edit-link">Edit</span>
 </div><!-- .comment-metadata -->

 <p class="comment-awaiting-moderation"></p>

 </footer><!-- .comment-meta -->

 <div class="comment-content"></div><!-- .comment-content -->

 <div class="reply"></div><!-- .reply -->

</article><!-- .comment-body -->

Keep in mind that is the very simplified version without any WordPress comment template tags. Just straight HTML5 markup. Some people don’t mind using that while others like to have more control and would like to style in a different way. In order to do that we have to pass an argument to the callback function argument.

Enter the callback

This is why you want to use a callback function to create and style the comment. In order to do this we pass the argument

'callback' => 'my_theme_comment'

in our array of arguments much like Twenty Twelve does. Next we have to create the actual function that will house our newly created and customized comment with custom markup. Where that function resides is entirely up to you.

Once we have created the function we can start with all the markup and comment template tags we so desire. I personally like to keep things fairly simple and just have the comment author, date and text. Often my code looks like:

function custom_comments( $comment, $args, $depth ) {
    $GLOBALS['comment'] = $comment;
    switch( $comment->comment_type ) :
        case 'pingback' :
        case 'trackback' : ?>
            <li <?php comment_class(); ?> id="comment<?php comment_ID(); ?>">
            <div class="back-link">< ?php comment_author_link(); ?></div>
        <?php break;
        default : ?>
            <li <?php comment_class(); ?> id="comment-<?php comment_ID(); ?>">
            <article <?php comment_class(); ?> class="comment">

            <div class="comment-body">
            <div class="author vcard">
            <?php echo get_avatar( $comment, 100 ); ?>
            <span class="author-name"><?php comment_author(); ?></span>
            <?php comment_text(); ?>
            </div><!-- .vcard -->
            </div><!-- comment-body -->

            <footer class="comment-footer">
            <time <?php comment_time( 'c' ); ?> class="comment-time">
            <span class="date">
            <?php comment_date(); ?>
            <span class="time">
            <?php comment_time(); ?>
            <div class="reply"><?php 
            comment_reply_link( array_merge( $args, array( 
            'reply_text' => 'Reply',
            'after' => ' <span>&amp;amp;darr;</span>', 
            'depth' => $depth,
            'max_depth' => $args['max_depth'] 
            ) ) ); ?>
            </div><!-- .reply -->
            </footer><!-- .comment-footer -->

            </article><!-- #comment-<?php comment_ID(); ?> -->
        <?php // End the default styling of comment

And there we have a custom comment that will be used instead of the default WordPress one.

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.