Ahmad Awais



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.

πŸ‘¨β€πŸ« Edutainer & teacher at VSCode.pro 🎩 Full-time #OpenSourcerer 🦊 Google Developers Expert for Web πŸ₯‘ OSS Developer Advocate 🌳 Node.js Foundation Community Committee Member πŸ”₯ Ridiculously hard-working Full Stack Web Developer πŸ˜‚ Hilarious comedian ⓦ Regular WordPress Core Developer πŸ“£ TEDx Speaker ✌️ Spends 50-80% of his time building professional FOSS (Free & Open Source Software) used by over 1,399,687 Developers πŸ™Œ Cloud Community Evangelist 🎯 JavaScript & DevOps fanboy πŸ’œ Loves his wife (Maedah) πŸ• Learn more about Ahmad ↣

Say πŸ‘‹ on Twitter @MrAhmadAwais | Subscribe to the Developer's Takeaway!


TheDevTakeaway: Developers' Newsletter!

Takeaway my professional opinion about Open Source, JavaScript/Cloud, Full Stack Development, building a business, growing a family, and everything in between! Delivered to your inbox once a month. 🀣 I'm even funny some times. πŸ‘» I hate spam! Pinky Promise!

πŸ”₯ CHECK OUT β†’