Adding a Set of Responsive Grid Shortcodes to Your WordPress Site

Adding a Set of Responsive Grid Shortcodes to Your WordPress Site

Tutorial Details
  • Program: WordPress
  • Version: 3.0+
  • Difficulty: Beginner
  • Estimated completion time: 30mins

Today we’ll be taking a basic custom grid created with CSS and integrating it into WordPress via shortcodes. I presume all you readers have a basic understanding of CSS so I won’t be covering any of that here, I’ll also presume that you have a WordPress theme setup already and we’ll just add bits in. Enough said, lets get stuck in!


Step 1: Our CSS Grid

Before we start, we’ll go ahead and create a css folder and then a file inside called grid.css. Because of the amount of mobile and tablet usage now days we’ll go ahead and add the responsive part for our grid too. I’ve gone ahead and commented this to help make it less confusing for anyone not already familiar with it.

/* ---------------------------------------------------------------------- */
/*  Custom Grid
/* ---------------------------------------------------------------------- */

.container {
	margin:0 auto;
	width:940px;
	position:relative;
}

.container .one-half,
.container .one-third,
.container .one-fourth,
.container .two-thirds,
.container .three-fourths {
	float:left;
	margin-right:20px;
}

.container .one-half.last,
.container .one-third.last,
.container .one-fourth.last,
.container .two-thirds.last,
.container .three-fourths.last {
	margin-right:0;
}

.container .one-half       { width:460px; }
.container .one-third      { width:300px; }
.container .one-fourth     { width:220px; }
.container .two-thirds     { width:620px; }
.container .three-fourths  { width:700px; }

/* ------------------------------------------- */
/*  Responsive Grid - 
/*		1. Tablet
/*		2. Mobile Portrait
/*		3. Mobile Landscape
/* ------------------------------------------- */

@media only screen and (min-width: 768px) and (max-width: 959px) {
	.container                 { width:748px; }
	.container .one-half       { width:364px; }
	.container .one-third      { width:236px; }
	.container .one-fourth     { width:172px; }
	.container .two-thirds     { width:492px; }
	.container .three-fourths  { width:508px; }
}

@media only screen and (max-width: 767px) {
	.container       { width:300px; }
	.container .one-half,
	.container .one-third,
	.container .one-fourth,
	.container .two-thirds,
	.container .three-fourths { width:300px; margin-right:0; }
}

@media only screen and (min-width: 480px) and (max-width: 767px) {
	.container       { width:420px; }
	.container .one-half,
	.container .one-third,
	.container .one-fourth,
	.container .two-thirds,
	.container .three-fourths { width:420px; margin-right:0; }
}

Step 2: Registering Our CSS Within WordPress

Before we can jump into making any shortcodes we’ll need to register the CSS file we just created. We’ll do this by using wp_register_style and wp_enqueue_style. Be sure to place this within your functions.php or another file which is linked to via the functions.php file. I’ve also gone ahead and wrapped this within a function but this isn’t necessary. Once we’ve called and registered our CSS file we’ll need to hook it using the add_action function.

if ( !function_exists('register_css') ) {

	function register_css() {

		wp_register_style('custom-grid', get_template_directory_uri() . '/css/grid.css');
		wp_enqueue_style('custom-grid');

	}

	add_action('wp_enqueue_scripts', 'register_css');
}

Step 3: Starting to Create Our Shortcodes

To keep everything clean we will create a new file called shortcodes.php to keep our shortcodes separate from any other functions, we’ll also need to link to this within our functions.php file.

// Include shortcodes
include 'shortcodes.php';

Step 4: The Shortcode API

The Shortcode API is brilliant, it allows users to create endless things with it. You can pass attributes and values through it. If you’d like to read up more on the Shortcode API, visit the Shortcode API page in the WordPress Codex. To see what shortcodes can do, we will show two paths for this.


Step 5: Shortcode Route 1

Because this is a grid, it will have columns (obviously) but when it gets to the last column we’ll need to define it being the last column because of how the custom grid has been coded. For example, if we had a main area of two-thirds and a sidebar of one-third. The sidebar will need defining as the last one in the row so we will add a class of last to it.

Now we’ll start creating our shortcode, we’ll start off with a basic one-half column shortcode. We start off with creating a function with a name of the shortcode. We’ll then pass two arguments of $atts and $content. The way shortcodes work is very simple, if you’re creating a shortcode like this all we need to do is return something. All we’ll return is a div with the class of one-half along with the content inside it. The last thing to do is to enable the shortcode for use within your WordPress themes. This is done via the add_shortcode function. This function accepts two parameters, the name used to access the shortcode and the function name of the shortcode. We have used ‘one_half‘ for the name to access the shortcode so we can use this within the editor by typing [one_half].

function one_half( $atts, $content = null ) {

	return '<div class="one-half">' . do_shortcode( $content ) . '</div>';

}

add_shortcode('one_half', 'one_half');

Now, if we look back we spoke about defining the last column. For this route we’ll simply created another shortcode but instead of [one_half], we’ll use [one_half_last] while changing the class name from <div class="one-half"> to <div class="one-half last">.

function one_half_last( $atts, $content = null ) {

	return '<div class="one-half last">' . do_shortcode( $content ) . '</div>';

}

add_shortcode('one_half_last', 'one_half_last');

Step 6: Shortcode Route 2

Okay, if you would prefer to not have to create two shortcodes for each column – one for the normal and one for the last column there is an alternative. Instead of creating two we could pass an attribute through our shortcode, for example [one_half last="yes"]. If no attribute is passed, this will not be used as a ‘last‘ column.

A majority of this will look similar, with the exception of some new stuff. We’ll need to extract the shortcode_atts (attributes) first. Next because we defined ‘last‘ as an attribute we’ll need to use an if statement to check whether this is a last column. We’ll do this by checking if $last equals yes, $position equals last. If not, $position equals nothing. Then we can return the same thing but adding the $position variable for the last column option. Now we can access this shortcode still with [one_half] but adding the ‘last‘ attribute and a value of yes – [one_half last="yes"].

function one_half( $atts, $content = null ) {

	extract( shortcode_atts( array(
			'last'   => ''
		), $atts ) );

	if ( $last == 'yes') {
		$position = 'last';
	}
	else {
		$position = '';
	}

	return '<div class="one-half ' . $position . '">' . do_shortcode( $content ) . '</div>';

}

add_shortcode('one_half', 'one_half');

Conclusion

Well guys, that was my first tutorial here at Wptuts+, I hope you learnt something today! Feel free to use the CSS grid or shortcodes in your projects! Until next time, let me know your thoughts in the comments!

Luke Spoor is lspoor on Codecanyon
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://bowesales.com Jesse

    Hey, I was just working on a columns shortcode and took a break to do some reading on wp.tutsplus for another shortcode function and this just came up when I refreshed. Nice work dude!

    Here’s what I used. Seems to do the trick for me. (Hopefully the code renders correctly)

    
    /* #COLUMNS
    ================================================== */
    
    //[column]
    function column_shortcode( $atts, $content = null )
    {
    	extract( shortcode_atts( array(
    	  'offset' =>'',
              'size' => '',
    	  'position' =>''
          ), $atts ) );
    	  if($offset !='') { $column_offset = $offset; } else { $column_offset ='one'; }
    		
          return '<div class="'.$column_offset.'-' . $size . ' '.$position.'">' . do_shortcode($content) . '</div>';
    
    }
    add_shortcode('column', 'column_shortcode');
    //[/column]
    
    

    and CSS

    
    /* #COLUMNS
    ================================================== */
    
    .one-half{ width:48%; }
    .one-third{ width:30.66%; }
    .two-third{ width:65.33%; }
    .one-fourth{ width:22%; }
    .three-fourth{ width:74%; }
    .one-fifth{ width:16.8%; }
    .one-sixth{ width:13.33%; }
    .one-half, .one-third, .two-third, .one-fourth, .three-fourth, .one-fifth, .one-sixth {
    	position:relative; margin-right:4%; margin-bottom: 2%; float:left;
    }
    
    .last{margin-right: 0px;}
    .first{margin-left: 0px;}
    
    /* All Mobile Sizes (devices and browser) */
    	@media only screen and (max-width: 767px) {
    .one-half, .one-third, .two-third, .one-fourth, .three-fourth, .one-fifth, .one-sixth {
        float: none;
        width: 100%;
    }
    	}
    
    
    • Luke Spoor
      Author

      Hey man, nice job on this! I guess my route would be easier should the use not know the exact sizes, they can just use [one_half] etc but your’s a perfectly good alternative! :)

      • http://bowesales.com Jesse

        Hey thanks!

        Yeah, I’ve seen this method used in other themes, I was messing around with the %’s when yours popped up.

        I really like what you’ve done with your function.

        Cheers.

      • http://freakify.com Ahmad Awais

        Really loved your way.
        I was doing it with %s and was messing up a lot of times when browsed my themes at iPad.

    • Cynthia Lara

      Hey very nice code!!!

      Still I have a question, because if you have the last position in a column it must render at the end another div with clear:both; property for the parent div to grow height automatically.

      How can one return two outputs?

      One if it is last position (with that div at the end) and one just as you have it?

      So I tried adding something like

      if ($position=’last’)
      { return
      ‘ ‘ .
      do_shortcode($content) . ”;
      }
      else
      { return
      ‘ ‘ .
      do_shortcode($content) . ”;
      }

      But it loads me two columns with the last position.

      PLEASE HELP :(

      • Cynthia Lara

        DUH LOL just figured it out… I was wrong about a tiny thing.

        It was

        if ($position==’last’)

        instead of

        if ($position=’last’)

        Hope this helps somebody :P

  • Pingback: Adding a Set of Responsive Grid Shortcodes to Your WordPress Site | Qtiva

  • Des

    Can’t clearly understand why we should follow this tutorial… to be honest I can’t even understand what’s the outcome!

  • http://philsmartdesign.com.au Phil

    Hey mate

    A little offside from your tutorial, but I don’t suppose you know of a way to count up the number of shortcodes before any callbacks are executed?

    I’m attempting something similar to this tutorial but I need to get the number of times a shortcode appears in order to determine how many columns will appear in the resulting html.

    Cheers

  • Mark

    It seems strange to use shortcode functions for layout grids, shouldn’t this just be in custom templates?

    • Danny

      Not really strange at all. This way the user can use a full width template for the page they’re creating, and then use these shortcodes to make any layout they want, rather than being only able to use custom templates that the theme author has made.

  • http://www.guideplease.com Dilawer Pirzada

    I want a plugin which automatically make css sprite for my Theme is there any?

  • zzap

    Hi, what a coincidence. I’m also working on shortcodes at the moment and looking around to see if I missed any useful ones. I like your method Luke, even though I always prefer percents.

    One little thing is overlooked in files for download. In shortcodes.php functions for thirds and fourths last columns have errors. Shortcode names are good but the functions they are assigned to need adding “_last”. Here are codes:

    add_shortcode(‘one_third’, ‘one_third’);

    add_shortcode(‘one_third_last’, ‘one_third’);

    Halfs are ok. Personally, I would give a different function name for option two as it gives error for having two same functions and maybe someone wouldn’t know how to fix it.

    Other than those little overlooks, great work. Keep up with it.

  • http://crakken.com Nick Rameau (Crakken)

    Hey, this is the Skeleton way of doing it, at least you could give them some credit: http://getskeleton.com

    • http://wp.envato.com/ Japh Thomson
      Staff

      Hi Nick, thanks for your comment. I think it’s fair to say many people do it this way, and I doubt the guys from Skeleton would claim otherwise.

    • Luke Spoor
      Author

      Hey Nick I can’t see where you’ve pulled Skeleton into the equation here, this is just a small little CSS grid created by myself.

  • Tim

    Nice tut. Given that the tut is labelled as Beginner, I think the only thing that would have made it better is if you had concluded with an example of the short code’s usage i.e. either the code itself or a screen shot demonstrating it wrapping some content.

  • Flickapix

    Would the widths not be better off as a percentage rather than pixel? Thats how i do mine

    • Luke Spoor
      Author

      This is all down to the user, some like pixels, some like percentages. I myself prefer pixels, don’t ask me why :)

  • http://maddisondesigns.com Anthony Hortin

    Looks great but any particular reason you’re not just using :first-child or :last-child to remove the margin instead of having to use a separate shortcode/class? I know IE support for last-child only goes back to ie9 but first-child is supported all the way back to ie7

    • Luke Spoor
      Author

      A lot of grid frameworks like Skeleton mentioned above don’t use this, they use the classes ‘Alpha’ & ‘Omega’ to remove the left or right margin respectively.

  • Monia

    Where is step 5?

    • http://wp.envato.com/ Japh Thomson
      Staff

      Oops! We skipped a number. Fixed now :)

  • http://www.fusiondevs.com/ Bruno

    For the :first-child and :last-child to work in this you would requiere a higher level element to act as a parent, containing all the columns between the 1st and the last one of a row. So instead of just using:

    [one-half] [/one-half]

    You would need to do it

    [row] [one-half] Lipsum [/one-half] [one-half] Lipsum [/one-half] [/row]

    We all know that nesting shortcodes is a nightmare for unexperienced WP users. So i think using an extra word or a class=”first” parameter is the way to go.

  • Pingback: Tweet Parade (no.35 Aug/Sep 2012) | gonzoblog.nl

  • Pingback: Adding Some Responsiveness to Your Current Theme - There is a Theme For That

  • Erica

    I like where you’re headed with this, but the source files available for download were not very helpful at all. I spent a lot of time fixing the mistakes I found in it rather than saving myself some time with a good start. Please review these before you share them with others!

  • Grzegorz

    I have fatal error, redeclaration of function… How can i fix it?