How to create your own WordPress shortcodes

thumbnailIn version 2.5 WordPress introduced shortcodes, and all of us have probably used them at one time or another. They usually come bundled with plugins, or even themes, and what they do is watch for when you insert something inside square brackets then replace that with some other content; it could be a simple sentence or it could be a massive PHP function, it all depends on what you instructed WordPress to do.

Bundled shortcodes are great, and speed up things considerably, but wouldn’t it be great to know how to create shortcodes of your own?

In this article I’ll take you through creating some simple WordPress shortcodes to help you create any functionality you like.

A simple shortcode

The shortcode API works very simply: first you need to create a callback function that will run anytime the shortcode is used; then you need to tie that function to a specific shortcode making it ready for use. The code is frequently placed in the functions.php file, but if you plan on having a lot of shortcodes, it makes sense to create a separate file and include that file in your functions.php file.

In our first example we want to create a shortcode that will create some lorem ipsum every time we type [lorem] into the editor. First we need to create the callback function that will return the lorem ipsum (in shortcodes we don’t echo anything, everything is returned):

function lorem_function() {
  return 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec nulla vitae lacus mattis volutpat eu at sapien. Nunc interdum congue libero, quis laoreet elit sagittis ut. Pellentesque lacus erat, dictum condimentum pharetra vel, malesuada volutpat risus. Nunc sit amet risus dolor. Etiam posuere tellus nisl. Integer lorem ligula, tempor eu laoreet ac, eleifend quis diam. Proin cursus, nibh eu vehicula varius, lacus elit eleifend elit, eget commodo ante felis at neque. Integer sit amet justo sed elit porta convallis a at metus. Suspendisse molestie turpis pulvinar nisl tincidunt quis fringilla enim lobortis. Curabitur placerat quam ac sem venenatis blandit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam sed ligula nisl. Nam ullamcorper elit id magna hendrerit sit amet dignissim elit sodales. Aenean accumsan consectetur rutrum.';
}

Next we need to add this shortcode to WordPress using the add_shortcode function in either our functions.php file or a file that’s being included in it, this function adds the shortcode and also ties it to the function we just created. add_shortcode only takes two arguments, the first one being the name we want this shortcode to have (what we will type between the square brackets) and the second one being the function we want to attach to that shortcode:

add_shortcode('lorem', 'lorem_function');

That is all it takes to create a simple shortcode in WordPress.

 

Adding parameters

Continuing with this dummy content idea, we often need images in our content when we preparing our mockups and these images need to be different sizes, so now we’ll create a shortcode to insert an image like this:

[picture width="500" height="500"]

When WordPress encounters this we want a function that will insert an image. It needs to read the width and height attributes, but just in case we’ll also provide default values so that it can be used without the attributes. Because we may not have an image available, we’re going to use the lorempixel.com service to provide us with a random image.

First we need to create the function:

function random_picture($atts) {
   extract(shortcode_atts(array(
      'width' => 400,
      'height' => 200,
   ), $atts));
return '<img src="http://lorempixel.com/'. $width . '/'. $height . '" />';
}

We named this function random_picture and since this shortcode will be able to take arguments we gave it the $atts parameter. In order to use the attributes we need two functions: the shortcode_atts which is a WordPress function that combines our attributes with known attributes and fills in defaults when needed; and the extract PHP function which, as the name suggests, extracts those attributes we set for our shortcode. Finally the function returns the value we want, in this case the HTML code for our image combined with the width and height variables.

The only thing left to do is register this shortcode:

add_shortcode('picture', 'random_picture');

Our shortcode is complete, when we type [picture] it will give us a random image 400 by 200, and if we use the attributes we can create an image of any size we please.

 

Conclusion 

Creating little shortcodes for things we use frequently definitely helps us when writing blog posts because you can do anything you please with shortcodes, it can be as simple as returning a sentence, or as complex as adding a form or the latest posts sorted by month.

 

Have you created helpful shortcodes for WordPress? What shortcodes do you wish existed? Let us know in the comments.

Featured image/thumbnail, shrink image via Shutterstock.

Over 4,300 Professional, High-Quality Icons – only $37!
How to create your own WordPress shortcodes

Source

Posted in Blog | Comments Off on How to create your own WordPress shortcodes

8 Things Every WordPress Developer Should Know

Advertise here with BSA

WordPress is certainly a great tool, and it’s quite easy to get started. You can count on a lot of good resources (like this humble blog) and you can even dig into WP’s source code if you know PHP quite well.

But also, it’s quite easy to get lost. There are a lot of options, a lot of solutions, and sometimes it’s way harder to find the best solution than just fixing an issue. Well, let’s see some basic tips and snippets to help you solve some everyday issues.

8 Things Every WordPress Developer Should Know

1. You really shouldn’t use query_posts()

The truth is, among many reasons, you shouldn’t ever use query_posts. This is the most simplistic version of the loop, but as jQuery code, it’ll run a lot of background operations that will mostly rely on the WP_Query (then get_posts) and will require you a lot of code to clean up the mess.

In short, WordPress will load the main query BEFORE calling template files, so if you call a query_post() in your index.php file you’re actually calling 2 queries since the first one was already called. And if you consider the background queries it’s actually 8 (since each WP_Query loads 4 queries, call posts, count posts, call metadata, call terms).

What you should do:

  • Use WP_Query object whenever you need multiple loops in a page. So, sidebar loops, secondary loops in a page template and anything like this will be better using this function
  • Use pre_get_posts filter to modify the main loop. If you need to modify in any way the main WordPress loop (pretty much the case that you would use query_posts) just go for the pre_get_posts filter since it modifies directly the main WP_Query object (instead of getting a new DB query)
  • Use get_posts() if you don’t need a loop. If you are just getting posts and don’t need the main loop functions you could use this one since it’ll return you a simple array of posts

2. Always enqueue your scripts & styles

When you are creating themes, plugins or customizing any of these you may need to load external files. But each WordPress can contain a lot of things, and if you call a JS library twice you can potentially break the site.

The simple solution is introduced with the wp_enqueue_script function, since you can load (and register) a library or script and make sure that you are loading only one copy of it. The same rule applies for styles, but they won’t cause too much damage. Still a good option for loading standard styles, like styling for jQuery plugins, or CSS for HTML bootstraps.

3. Cache your stuff

8 Things Every WordPress Developer Should KnowImage from Kevin Andersson

If you are a plugin developer you should know the transients API. They allow you to store “options” for a small amount of time. So, if you are getting latest tweets, for instance, there’s no point in loading them all the time, you can set a transient for it and only load every 15 minutes or so.

The great thing about it is that you can cache your entire query on it. So if your blog is updated once a day you can set a transient that expires every 12h or less and you’ll be fine.

4. Know all your feeds

It’s always good to provide your usual feeds to your users, but sometimes we need a little bit more. Actually there are quite a lot of cool feeds that you can use:

  • Main – site.com/feed
  • Main comments – site.com/comments/feed
  • Post comments – site.com/post-name/feed
  • Categories & tags – site.com/category/categoryname/feed or site.com/tag/tagname/feed
  • You can also include / exclude categories like this – site.com/?cat=42,25,17&feed=rss2 or this site.com/?cat=-123&feed=rss2
  • Author – site.com/author/authorname/feed/
  • Search – site.com/?s=searchterm&feed=rss2
  • Custom Post Type – site.com/feed/?post_type=yourposttype
  • Custom Taxonomy – site.com/feed/?post_type=custom_post_type_name&taxonomy_name=taxonomy

5. How to add featured image in your feed

8 Things Every WordPress Developer Should KnowImage from Dash

This one is quite simple but gives a good final result (especially if your users are running a nice RSS reader like feedly that displays the main images). This code will do it (in your functions file):


function featured_image_in_feed( $content ) {

    global $post;

    if( is_feed() ) {

        if ( has_post_thumbnail( $post-&gt;ID ) ){

            $output = get_the_post_thumbnail( $post-&gt;ID, 'medium', array( 'style' =&gt; 'float:right; margin:0 0 10px 10px;' ) );

            $content = $output . $content;

        }

    }

    return $content;

}

add_filter( 'the_content', 'featured_image_in_feed' );

Source: WordPress: Add featured image to RSS feed/

6. Optimize your DB once a while

You can use either a plugin or manually but it’s always good to optimize your MySql tables often (at least once or twice a month) so you’ll ensure that your queries are as good as they can be, and will reduce your DB size

7. Enable GZIP

Imagine how great would it be if you could compress your site files before sending them to the user? Well, with server-side GZIP you can do that. And it’s fairly simple, you can add this snippet to your .htaccess file and you’re good to go:


#Gzip

<ifmodule mod_deflate.c>

AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript text/javascript

</ifmodule>

#End Gzip

Source: Enabling Gzip in .Htaccess

8. There’s a plugin for that

Even if you are not a developer you could improve your site performance with caching plugins, DB optimization plugins, CSS and JS minifying plugins.

Posted in Blog | Comments Off on 8 Things Every WordPress Developer Should Know