17. Shortcodes and Custom Functions


Image

PHP functions can’t be implemented in content, widgets, and many other areas, so pulling in a list of recent posts, galleries, ads, and other things can be difficult. Shortcodes are predefined functions in a simple format that you can set to let user admins call PHP functions in their content.

You can also create and then later call your own custom functions. There are countless reasons to write your own functions into your WordPress theme. Anytime you implement the same code over and over, it makes sense to pull it out, make it a function, and then call in your theme. Remember that it’s good practice to remove duplicate code as much as possible.

What you’re about to learn

• How shortcodes work

• How to write custom shortcodes

• How to implement shortcodes in content and widgets

• How to write and implement custom functions

• How to use conditional statements to determine when to incorporate an element

Shortcodes

Shortcodes empower user admins to perform functions that they would otherwise be unable to do. You can’t put PHP code into your content editor, so shortcodes do all the work of a PHP function in an easily writable fashion. A very simple example of a shortcode might be a blog that needs a legal disclaimer at the end of any post written by a lawyer.

There are several ways to do this, but a shortcode is a quick and simple solution. The author of the post could put [disclaimer] in the content editor at the bottom of every post. The shortcode API would interpret this as a call to a PHP function, run that code, and return the preset disclaimer as content. There are hundreds of ways to use shortcodes, and since they even accept parameters, you can do a lot with them.

A Shortcode Example

Let’s create a simple shortcode for the legal disclaimer example above. First we’ll define the shortcode and the corresponding function to perform in the functions.php file. Then we’ll use the shortcode in some content.

Start by opening functions.php. Remember to try and keep your related code consolidated and neat, and comment your code as much as possible so that everyone reading it, including you, will understand the where and why. Insert the following code:

add_shortcode( 'disclaimer', 'j2theme_legal_disclaimer' );

Here we’re calling a WordPress function called add_shortcode(). This function accepts two parameters: the title of the shortcode and the function to call when the shortcode is implemented. For more information on add_shortcode, go to http://wdgwp.com/add_shortcode.

Next, create the j2theme_legal_disclaimer function. In this function we want to return some HTML markup with the disclaimer content, so place the following code above the add_shortcode() function:

function j2theme_legal_disclaimer(){
  return '<small>Before taking any legal advice you should always consult an
        attorney.</small> ';
}

This code is really no different from many of the other PHP functions we’ve talked about in this book. It performs one task and returns the <small></small> tags for outputting with the rest of the content.

Finally, implement the shortcode. Go to any posts and insert [disclaimer] into the content. Remember the content between the square brackets is the name of the shortcode you defined in the add_shortcode() function. Figure 17.1 shows the shortcode implemented in a fake post.

Image

Figure 17.1. Inserting the [disclaimer] shortcode.

This outputs the following HTML:

<p>Welcome to my legal blog. Here we give a ton of legal advice and offer a
        lot of help to our readers. Thanks for visiting and please comment
        and share often.</p>

<small>Before taking any legal advice you should always consult an attorney.
        </small>

Since shortcodes return HTML anywhere we place them, we can insert [disclaimer] in the middle of a paragraph. This lets the attorney insert the disclaimer alongside the specific text that’s being referred to.

Image

Figure 17.2. Inserting the [disclaimer] shortcode mid-paragraph.

Figure 17.2 shows the disclaimer shortcode in the middle of the content that outputs the following HTML:

<p>Welcome to my legal blog. Here we give a ton of legal advice and offer a
        lot of help to our readers. <small>Before taking any legal advice you
        should always consult an attorney.</small> Thanks for visiting and
        please comment and share often.</p>

You can create many shortcodes to perform multiple tasks. There really are no limits on the number of shortcodes you can write into your theme or plugin.

A Shortcode with Attributes

In this example, we’ll add some functionality to the shortcode by giving the user admin the ability to pass parameters to our function. Let’s create a shortcode that returns the embed code needed to frame in a Vimeo video.


Note

oEmbed lets you easily embed videos and other media with associated sites. You can embed Vimeo, YouTube, and other videos simply by placing the video URL in the content editor. You can read more about oEmbed at http://wdgwp.com/oembed. (We’re creating the same function with our shortcode, as an example.)


When you copy the following code into your functions.php file, you’re declaring a new shortcode called “vimeovid” that calls the custom j2theme_vimeo_vid() function:

add_shortcode( 'vimeovid', 'j2theme_vimeo_vid' );

When placed above the add_shortcode() function, this function returns the <iframe> markup needed to embed the Vimeo video:

function j2theme_vimeo_vid( $atts ){
  return '<iframe src="http://player.vimeo.com/video/{$atts[id]}?title=0&a
        mp;byline=0&amp;portrait=0&amp;color=ff3333" width="{$atts[width]}"
        height="{$atts[height]}" frameborder="0" webkitAllowFullScreen
        mozallowfullscreen allowFullScreen></iframe>';
}

This time things may appear a bit different. We’re still “returning” some markup, but now we have variables in place of some of the content. Take note that this function now accepts the parameter $atts, which lets you pass variables from the shortcode to the function. These parameters come to the function in the form of an array. Since we’re using the PHP return statement we can evaluate the $atts array with curly brackets. This may seem a bit advanced, but let’s walk through it.

Now that our functions are in place, we can insert a shortcode into the content. The short-code in Figure 17.3 looks similar to the previous example, except this time it has specific parameters and values assigned inside it.

Image

Figure 17.3. Video shortcode with parameters.

When we pass a parameter of id with the value of “28730350” into our function, the $atts array will hold the key/value pair. We can then return the value of the id by writing {$atts[id]}. The curly braces let us evaluate the array before it’s returned.

Inserting [vimeovid id=”28730350” width=”500” height=”375”] into the content editor outputs the following HTML. Notice that the ID, width, and height in the HTML exactly match the parameters passed in the shortcode:

<iframe src="http://player.vimeo.com/video/28730350?title=0&amp;byline=0&amp;
       portrait=0&amp;color=ff3333" width="500" height="375" frameborder="0"
       webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

When you write your shortcodes, you can replace any parameters you pass with in the square brackets of the $atts array. There are several ways to parse that array—this is just one suggestion.

This code example makes it easy for a user admin to embed a Vimeo video and change the width and height of the <iframe>. You can translate what we did here to any number of examples and build out a great deal of added functionality in your theme.

Enclosed Shortcodes

In the code example above, we created an opening and closing shortcode so we could wrap it around content. In the next chapter, we’ll use this technique to show and hide content based on whether or not a user is on a mobile device. For now we’ll just wrap some arbitrary content in a <span></span> tag to get used to writing shortcodes like this.

Let’s assume the theme does something unique to any <span> tag with a class of “featured.” Instead of forcing the user admin to know or write HTML to add this benefit we can instruct him to use our shortcode.


Note

Shortcodes can be placed in both the visual and the HTML editor. The shortcode is evaluated upon the rendering of content in The Loop, so it doesn’t matter how the shortcode is placed. This is because the shortcode isn’t really code or markup—it’s like more like a WordPress hook that we create.


Insert the following code into the functions.php file, as we’ve done twice already:

function j2theme_span_wrapper( $atts, $content='' ){
  return '<span class="featured">{$content}</span>';
}
add_shortcode( 'spanwrap', 'j2theme_span_wrapper' );

Then use the add_shortcode() function to create the shortcode and the function call. In the function j2theme_span_wrapper(), you’re now passing a $content as a new parameter and you’ll “return” the content wrapped in the <span></span> tags for output.

Figure 17.4 shows the new shortcode wrapped around some content. Notice that the closing shortcode uses a / (forward slash) similar to the URLs of HTML markup. Inserting this code outputs the following HTML, which gives the user admin the desired effect:

<p>Here is some <span class="featured">Featured Content</span> that will be
        displayed in some really cool manner.</p>

Image

Figure 17.4. Enclosed shortcode.

These examples should help you understand building shortcodes into your themes and plugins. Since these were just learning examples you can remove the shortcodes from your functions.php file. We’ll create our shortcodes in the next chapter. For more information about the shortcode API, go to http://wdgwp.com/shortcode_api.

Shortcodes are widely used in WordPress. Some great plugins, like Contact Form 7, rely heavily on shortcodes to make it easy to embed forms throughout a site. If you’ve used WordPress in the past you probably implemented a shortcode, possibly without even knowing it. From now on take special care to note if you’re implementing some added functionality by wrapping content in square brackets.

Custom Functions

A semantic and well-thought-out theme will often pull segments of code out of template files and replace them with functions. For example, many of our template files use the same code for our loop. If the loop code is the same then it only makes sense to isolate it to a single location. This way if we have to make a change to it we need only do it once, not multiple times.

Advanced WordPress theming is beyond the scope of this book, so for now we’ll use this strategy on a single WordPress call to build a foundation. You can build on this example throughout the theme if you so choose.

We’re going to write a custom PHP function to create pagination navigations in our theme. Instead of duplicating this WordPress call in several template files, we’ll be able to call a single function we create.

Start by jumping back into the functions.php file. Here, we’ll create our function and return our paginated links. The following code is the most advanced we’ll write in this book. Go ahead and copy it, then we’ll go over it in detail:

function j2theme_paginate() {
  global $paged, $wp_query;
  $abignum = 999999999; //we need an unlikely integer
  $args = array(
    'base'             => str_replace( $abignum, '%#%',
        esc_url( get_pagenum_link( $abignum ) ) ),
    'format'           => '?paged=%#%',
    'current'  => max( 1, get_query_var( 'paged' ) ),
    'total'    => $wp_query->max_num_pages,
    'show_all'        => False,
    'end_size'        => 2,
    'mid_size'        => 2,
    'prev_next'=> True,
    'prev_text'=> __( '&lt;' ),
    'next_text'=> __( '&gt;' ),
    'type'    => 'list'
  );

  echo paginate_links( $args );
}

The first line defines the function with the name j2theme_paginate. The second line uses PHP global scope to give us access to $paged and $wp_query values. Sometimes putting code inside a function is like stocking a bunker: The only supplies (variables) you’ll have access to are the ones you bring into the bunker (function) with you. Using the global scope property we can gain access to the values that are defined outside the function. For more on PHP and scope, go to http://wdgwp.com/scope.

Next, create a variable called $abignum, which we’ll need for the function to perform some calculations. Just create a very large number that will be unlikely to ever be used in a pagination nav. The next line starts an array that we’ll fill with parameters to be passed to the paginate_links() function. This function accepts many parameters, some of which may be a bit confusing because we’re actually performing functions inside of functions inside of parameter calls. Here’s a list of links that provide detailed documentation on everything we just used:

• str_replace()—http://wdgwp.com/str_replace

• esc_url()—http://wdgwp.com/esc_url

• max()—http://wdgwp.com/max

• get_query_var()—http://wdgwp.com/get_query_var

• _ _() - http://wdgwp.com/_2

• paginate_links() - http://wdgwp.com/paginate_links

The last bit of this function echoes what is returned by the paginate_links() function, which means that anywhere we place the following code, our paginate function will run and return the pagination navigation:

<?php j2theme_paginate(); ?>

Make sure you call the j2theme_paginate() function in The Loop. Go ahead and replace the pagination static markup in the theme files with this function. Below is an example of the HTML this function will output. It will vary depending on the number of pages of content the site has to display:

<ul class='page-numbers'>
  <li><span class='page-numbers current'>1</span></li>
  <li><a class='page-numbers' href='http://localhost/j2-theme/page/2/'>2
        </a></li>
  <li><a class='page-numbers' href='http://localhost/j2-theme/page/3/'>3
        </a></li>
  <li><span class="page-numbers dots">&hellip;</span></li>
  <li><a class='page-numbers' href='http://localhost/j2-theme/page/10/'>10
        </a></li>
  <li><a class='page-numbers' href='http://localhost/j2-theme/page/11/'>11
        </a></li>
  <li><a class="next page-numbers" href="http://localhost/j2-theme/
        page/2/"
>&gt;</a></li>
</ul>

The ability to call a complex function like paginate_links() without having to duplicate the parameters saves a lot of time. You can duplicate this strategy in many other areas of the template files. As an exercise, try locating other areas of duplicated code and replacing them with custom functions. These custom functions don’t have to be complex. You can write your own to perform multiple complicated tasks or simply return a value.

Shortcode or Custom Function

Whether you’re using a shortcode or a custom function, the goal is to reduce the effort in displaying content or performing some functionality. Shortcodes are typically used by user admins, so they can do something that would otherwise be out of the realm of their expertise. And I often write shortcodes for myself so I don’t have to recall specific HTML markup if I’m performing a task over and over again.


Note

Using shortcodes in widgets is not inherently available. You have to activate this ability by placing the following code into the functions.php file:

add_filter( 'widget_text', 'do_shortcode' );

Once you do this you will be able to put shortcodes in widgets for an added benefit to the User Admin.


Shortcodes should be used in content, whereas custom functions are meant to be used in theme files. There are ways to use shortcodes in a theme file. For example, the code below performs our Vimeo shortcode functionality in a template file:

<?php echo do_shortcode( '[vimeovid id="28730350" width="500"
        height="375"]' ); ?>

Conditional Statements

There may be times when you need to show something in a template file, but only if you’re on the home page. At other times you might want to perform a specific function on a post rather than a page or visa versa. Conditional statements let you test for the existence of elements or the user’s current location in the theme, then perform an action based on the outcome.

In PHP, an if statement tests for something to be true and, if it is, proceeds. If it isn’t, it does something “else.” Read more about if statements at http://wdgwp.com/php-conditionals.

Several WordPress functions exist solely for testing these conditions. For example, if you want to display a link in the footer of your site only when the user is on a post, you could write the following:

<?php
  if( is_single() ) {
    echo '<a href="http://domain.com">My Link</a>';
  }
?>

In the above example, if the is_single() function returns true, the <a> tag will be echoed. Otherwise nothing will happen. The is_single() function returns true only if the user is currently viewing a post. There are several other conditional tags available, the most common of which I’ve listed below. To read more about WordPress conditional tags, go to http://wdgwp.com/conditional_tags.

• is_home()—http://wdgwp.com/is_home

• is_front_page()—http://wdgwp.com/is_front_page

• is_single()—http://wdgwp.com/is_single

• is_page()—http://wdgwp.com/is_page

• is_category()—http://wdgwp.com/is_category

• is_404 - http://wdgwp.com/is_404

If you master PHP conditional tests it’ll be easy to build out your themes using these functions.

What’s Next

We’ve come a long way and are now implementing some pretty advanced code. Shortcodes and custom functions can take your theme to a whole new level. In the next chapter, we’ll make the theme responsive. The HTML and CSS are already done; all we have to do is overcome some WordPress-related hurdles so user admins can maintain the integrity of the responsive layout.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.67.84