Good Ideas

bootstrap shortcode

A WordPress shortcode for smartly manage Bootstrap scaffolding

Posted by:

|

On:

|

During the development of my last wordpress theme, I had the need to manage the layout columns in a easy way. So I write a little WordPress shortcode that I want to share with you.

bootstrap shortcode

Probably the majority of buyers of my theme doesn’t know the principles of web development, nor even how Twitter Bootstrap works. So I don’t want disturb them with a lot of shortcodes just only for follow Bootstrap paradigm. In particular, the Bootstrap concept of “row” and “span” have to be translated into two shortcode.

I want to process them into a only one shortcode, called “cols”. The user should be more familiar with the concept of columns and so I’ll make his life easier.

The shortcode

Let’s go deeper into code. The default Bootstrap scaffolding use 12 columns. The problem is to insert a row every 12 columns. The solution adopt a global variable $cols to count the number of current columns. Before the first column a row-fluid column markup is opened and after the twelfth the markup is closed.

Here is the final shortcode function:

/**
* Create all the markup needed to manage rows and span and
* create columns in the document layout.
*
* @since Soave 1.0
*
* @param array $attrs Default n=1.
* @return string Columned layout.
*/

function soave_cols( $atts, $content = null) {
  global $cols;
  $open_row = "";
  $close_row = "";

  // Extract parameter and normalize it
  extract( shortcode_atts( array(
    'n' => '1'
    ), $atts ) );
  $n = intval($n);

  // if it is the first, open the row
  if ($cols == 0) {
    $open_row = '<div class="row-fluid">';
  }

  $cols += $n;

  // if cols >= 12 the row have to be closed
  if ($cols >= 12) {
    $close_row = '</div>';
    $cols = 0;
  }

  // produce the html
  $out .= $open_row . '<div class="span' . $n . '">';
  $out .= do_shortcode($content);
  $out .= '</div>' . $close_row;

  return $out;
}

…where $cols is the global variable.

This solution should remove all the strange shortcodes that are found in various themes around the net, such as [one_third], [two_third] or [column_last] and so on. However this automatic columns calculation require precision and so the user must be looking forward to create rows with only 12 columns.

Examples

Some wrong example:

[cols n=4]Lorem Ipsum[/cols]
[cols n=9]Lorem Ipsum[/cols]

The sum is 13 and the layout break. The right example is:

[cols n=4]Lorem Ipsum[/cols]
[cols n=8]Lorem Ipsum[/cols]

The sum is 12 and the layout is consistent.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *