Ahmad Awais

SHARE


Code Your First Shortcode in WordPress

Ahmad AwaisAhmad Awais

Shortcode API in WordPress is fun. It helps you create small tags to address aΒ chunk of code. All you do is write some [tag] and it returns the HTML/CSS/PHP code which you have saved inside it. Shortcodes can be used both in the Visual & the Text tab of your post/page editor. Let’s build a basic shortcode.Β Building shortcodes is fun.Β AΒ beginner can easily code a shortcode in underΒ one minute. Shortcodes are based upon a philosophy called DRY i.e. Don’t Repeat Yourself. E.g. I link [aboutme] page in my blog posts a lot. Same is the case with [contact] page link. Instead of writing these links each and every time, I have created shortcodes to help me optimize my workflow.

Β Coding a Shortcode in WordPress

The algorithm of using shortcode API in WordPress is quite a simple one. All you have to do is write a function, return something and register a tag, which is then later used to render the shortcode. Let’s take an easy example;

I am going to create a basic shortcode which will help me in linking to my [aboutme] page in form of a shortcode [ aa_me]. So, I registered a function aa_me_shortcode() which is returning some HTML code(the code between return’HTML/CSS_CODE‘;). After that add_shortcode() function is registering [aa_me] against the same aa_me_shortcode() function.

Modify this code, and paste it inside your theme’s functions.php file. At the very end before the closing PHP tag i.e. ?>. Don’t copy the <?php ?> tags from the code.
After saving the file go to the editor and type [aa_me] to render the shortcode. That’s about it. Enjoy building awesome shortcodes.

Two More Shortcodes

I have coded two more shortcodes for you people. One is for custom placement of Adsense or any other ads code. Other one hides the content inside it from users who are not logged in. Usage examples are given inside the code in a commented form.

🎩

WPTakeaway: Premium WordPress Newsletter!

Takeaway my professional opinion about Full Stack WordPress Development, building a business, growing a family, and everything web! Delivered to your inbox twice a month. πŸ‘» I hate spam! Pinky Promise!

πŸ₯‘ OSS Developer Advocate πŸ”₯ Ridiculously hard-working Full Stack Web Developer ⓦ Regular WordPress Core Contributor πŸ“£ TEDx Speaker ✌️ Spends 50% of his time building FOSS (Free & Open Source Software) used by over 91,300 Developers πŸŽ– WordPress Advocate & πŸ™Œ Community Evangelist 🎯 JavaScript & DevOps fanboy πŸ˜‚ Cracks silly jokes πŸ’œ Loves his wife (Maedah) πŸ• Learn more about Ahmad ↣

Say πŸ‘‹ on Twitter @MrAhmadAwais | Subscribe to the WordPress Takeaway!