How to Use Custom PHP Functions and Shortcodes in WordPress

I touched on this subject before in my previous article titled WordPress Tip: the_category Without Links, which focuses on the WordPress get_category function, but I decided to write this article so I can focus more on the general implementation of PHP functions with WordPress, and so that people will have an easier time locating these tips via a web search.

Some WordPress plugins require you to add shortcodes to your pages/posts to utilize the plugin, so I wouldn’t be surprised if you were already using shortcodes. Whether or not you’ve had any experience using WordPress shortcodes, this tutorial has what you need to get started.

Step 1: Create the user-functions.php file

The user-functions.php file will contain our custom functions and shortcodes.

Create a new text file named user-functions.php and copy/paste the following code into the file:

<?php
function HelloWorld() {
    return "Hello World! This is my custom shortcode.";
}
add_shortcode('hello', 'HelloWorld');
?>

What we’ve done here is create one function called HelloWorld (lines 2-4), and then we added a shortcode to WordPress (line 5) named hello, which calls the HelloWorld function when we include the [hello] shortcode in the contents of a page or post.

Save this file and upload it to your active theme folder. For example, if you are using the Twenty Ten theme, the file should be located under [WordPressDir]\wp-content\themes\twentyten\user-functions.php.

Step 2: Instruct WordPress to load the user-functions.php file

Unless WordPress loads your user-functions.php file, it won’t even know about your custom functions/shortcodes!

Download functions.php from your active theme folder.

Open the functions.php file in a text editor and add the following line of code anywhere on a new line:

include_once (TEMPLATEPATH . '/user-functions.php');

Here we are instructing WordPress to load our user-functions.php file as soon as it loads the functions.php file, which will make our custom functions/shortcodes available throughout the entire site, as long as the active theme that we are modifying remains active.

Save the functions.php file and upload it back to your root WordPress directory, overwriting the old one.

Step 3: Using the Shortcode in a Page/Post

Create a new page, then write the following text in the visual editor:

[hello]

This shortcode will instruct WordPress to call your HelloWorld function. When you view the published page (or preview the draft), you should get a result similar to this:

Hello World! This is my custom shortcode.

Conclusion

I’ve purposely kept this tutorial and the source code simple enough for anyone to grasp the the basics of what it takes to add a function/shortcode to WordPress. I may decide to extend this tutorial in the future and include some intermediary/advanced topics for readers who wish to continue learning the simple way, via this tutorial.

Related

Tags: , ,

14 Comments

  1. Thanks for the article. I’m a little lost with shortcodes. I see that some of them have to be made and added to a php file, but it also looks like some already exist inherently and all I’m supposed to do is put the shortcode in a page or post? For example, to get a contact form, WordPress codex simply says add [contact-form] to a page or post. I do that and nothing happens. Is there more that I’m supposed to do? Thank you so much

    • Hi Jon, pretty late on my reply I’ve realized but I do have an answer I think. You said the WordPress Codex says add [contact-form] but I’m not seeing this information anywhere in the Codex. I do think that WordPress.com (a hosted WP platform with extra features) offers this shortcode, but it doesn’t look to come with the WordPress.org (Codex) package by default. You’d have to use a plugin like Fast Secure Contact Form, then use their shortcode to include it in a page/post.

  2. Thanks – exactly the information I was hunting for (I hope). Lookign to create my own shortcode for including RSS feeds in my pages and posts. There are numerous plugins to do that but none I have found that fully render the feeds with images etc. So I have been relying on a manual php section in my index.php fileld with ‘if else page=x’ etc

    Hopefully this plan will work!

  3. Hmmm – following up on previous comment, I have a coupel of issues – hoping you can advise.

    1. Following your exact procedures, the “Hello World! This is my custom function.” appears at the top of the post, no matter where in the post I add the shortcode.

    2. How do I pass a parameter to the function through the shortcode. e.g. in your example let’s say we want it to say, “”Hello World! My name is xxx.” – How would we implement the name variable into the add_shortcode line of code, and how to add it in the shortcode itself?

    Thanks again.

  4. Hey kev, Jon, thank you very much for the constructive comments. Just dropping this quick reply to let you know I’ll be answering your questions.

  5. Jon, what you are seeing is actually from WordPress.com and not the WordPress.org Codex (unless you can point me in the right direction – I couldn’t find it there). WordPress.com is a WordPress blog hosting service and they run a modified version of the WordPress software which adds the [contact-form] shortcode that you are mentioning, as well as several other shortcodes and features. I was plenty confused by this at first, just like you. That’s partially why I wanted to write these tutorials.

    If you want to use a contact form on a self hosted WordPress blog, check out one of the various Contact Form plugins at the WordPress.org Extend page.

  6. All sorted now – with further help from http://codex.wordpress.org/Shortcode_API

    Thanks again

  7. @kev_martin,

    1. I believe this happens because WordPress processes shortcodes after the page has been rendered when it calls the_content, and echo seems to just render to the top of the page. You can modify the code above to return the string rather than echo the string, which should place it exactly where the shortcode appears in your post/page. Like this:

    function HelloWorld() {
        return "<p>Hello World! This is my custom function.</p>";
    }
    

    Notice the <p> tag which helps it appear like a paragraph would in your post/page.

    2. You need to modify the function and shortcode slightly.

    Change the function so it accepts the $atts argument. The $atts argument is an array containing however many attributes that we have chosen to pass to the function via the shortcode in a post/page. In this example we are only passing one attribute (name), so we extract $atts to put the first attribute into a variable called name ($name), whose value equals whatever we specify in the shortcode, unless we don’t specify a value in which case a default name of ‘Nobody’ is used:

    function HelloWorld($atts) {
        extract(shortcode_atts(array('name' => 'Nobody',), $atts));
        return "Hello World! My name is $name.";
    }
    

    Then change the shortcode in your post/page so it passes a value for the name parameter to the function.

    [hello name="perry"]
    

    Someone feel free to correct me if I’m wrong, I’m only a few weeks into PHP and WordPress development ๐Ÿ™‚

  8. @kev_martin, looks like you have it figured out. I noticed a pending comment while I was still writing you an answer, guess I should have checked it!

  9. Yep – I did indeed. But thanks for making the effort anyway – I’m sure others will benefit from the explanation ๐Ÿ™‚

  10. Patrice Hinton says:

    This just saved my life THANK YOU! I am not a programmer and I have a short code that has been giving me hell for over a week. I can’t launch my website without it.

    Again, Thank YOU!!!!!!!!

    • Thank you Patrice, it’s good to know this tip still works. I just noticed and corrected some errors in the code of this article, hopefully that clears up some confusion.

  11. Brad Maunsell says:

    Great article.
    I am a beginner in the process of learning PHP for use in WordPress. I have been struggling for a long time and this is the first article I have found that makes sense to me – simple and my Hello World is actually working!

    • That’s good to hear Brad. I try to write for people of all ages and technical backgrounds. It seems to be working out. ๐Ÿ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *