𝗛𝗼𝘄 𝘁𝗼 𝗖𝗿𝗲𝗮𝘁𝗲 𝗖𝘂𝘀𝘁𝗼𝗺 𝗦𝗵𝗼𝗿𝘁𝗰𝗼𝗱𝗲𝘀 𝗳𝗼𝗿 𝗗𝘆𝗻𝗮𝗺𝗶𝗰 𝗖𝗼𝗻𝘁𝗲𝗻𝘁 𝗶𝗻 𝗪𝗼𝗿𝗱𝗣𝗿𝗲𝘀𝘀

hortcodes are a fantastic way to add reusable content or functionality to WordPress sites with minimal effort. Today, let’s explore how to create custom shortcodes that display dynamic content, such as user data or recent posts.

𝗦𝘁𝗲𝗽 𝟭: 𝗥𝗲𝗴𝗶𝘀𝘁𝗲𝗿 𝗮 𝗕𝗮𝘀𝗶𝗰 𝗦𝗵𝗼𝗿𝘁𝗰𝗼𝗱𝗲
In your theme’s 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯𝘴.𝘱𝘩𝘱 file or a custom plugin or mu-plugin, you can register a shortcode using the 𝘢𝘥𝘥_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦 function.

𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘮𝘺_𝘤𝘶𝘴𝘵𝘰𝘮_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦() {
𝘳𝘦𝘵𝘶𝘳𝘯 “𝘏𝘦𝘭𝘭𝘰, 𝘞𝘰𝘳𝘥𝘗𝘳𝘦𝘴𝘴!”;
}
𝘢𝘥𝘥_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦(‘𝘨𝘳𝘦𝘦𝘵𝘪𝘯𝘨’, ‘𝘮𝘺_𝘤𝘶𝘴𝘵𝘰𝘮_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦’);

Now, simply add [𝘨𝘳𝘦𝘦𝘵𝘪𝘯𝘨] to any post or page, and WordPress will output “Hello, WordPress!” 🚀

𝗦𝘁𝗲𝗽 𝟮: 𝗔𝗱𝗱 𝗗𝘆𝗻𝗮𝗺𝗶𝗰 𝗖𝗼𝗻𝘁𝗲𝗻𝘁
Next, let’s modify the shortcode to display dynamic content, such as the current user’s name.

𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘶𝘴𝘦𝘳_𝘨𝘳𝘦𝘦𝘵𝘪𝘯𝘨_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦() {
$𝘤𝘶𝘳𝘳𝘦𝘯𝘵_𝘶𝘴𝘦𝘳 = 𝘸𝘱_𝘨𝘦𝘵_𝘤𝘶𝘳𝘳𝘦𝘯𝘵_𝘶𝘴𝘦𝘳();
𝘳𝘦𝘵𝘶𝘳𝘯 ‘𝘏𝘦𝘭𝘭𝘰, ‘ . 𝘦𝘴𝘤_𝘩𝘵𝘮𝘭($𝘤𝘶𝘳𝘳𝘦𝘯𝘵_𝘶𝘴𝘦𝘳->𝘥𝘪𝘴𝘱𝘭𝘢𝘺_𝘯𝘢𝘮𝘦) . ‘!’;
}
𝘢𝘥𝘥_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦(‘𝘶𝘴𝘦𝘳_𝘨𝘳𝘦𝘦𝘵𝘪𝘯𝘨’, ‘𝘶𝘴𝘦𝘳_𝘨𝘳𝘦𝘦𝘵𝘪𝘯𝘨_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦’);

This will greet logged-in users by name. If the user is not logged in, you can add logic to show a generic greeting.

𝗦𝘁𝗲𝗽 𝟯: 𝗨𝘀𝗲 𝗦𝗵𝗼𝗿𝘁𝗰𝗼𝗱𝗲 𝗔𝘁𝘁𝗿𝗶𝗯𝘂𝘁𝗲𝘀
You can extend shortcodes by adding attributes to make them more flexible. For example, let’s create a shortcode that displays recent posts with a customizable post count.

𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘳𝘦𝘤𝘦𝘯𝘵_𝘱𝘰𝘴𝘵𝘴_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦($𝘢𝘵𝘵𝘴) {
$𝘢𝘵𝘵𝘴 = 𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦_𝘢𝘵𝘵𝘴(
𝘢𝘳𝘳𝘢𝘺(
‘𝘤𝘰𝘶𝘯𝘵’ => 5,
),
$𝘢𝘵𝘵𝘴,
‘𝘳𝘦𝘤𝘦𝘯𝘵_𝘱𝘰𝘴𝘵𝘴’
);

$𝘳𝘦𝘤𝘦𝘯𝘵_𝘱𝘰𝘴𝘵𝘴 = 𝘸𝘱_𝘨𝘦𝘵_𝘳𝘦𝘤𝘦𝘯𝘵_𝘱𝘰𝘴𝘵𝘴(𝘢𝘳𝘳𝘢𝘺(‘𝘯𝘶𝘮𝘣𝘦𝘳𝘱𝘰𝘴𝘵𝘴’ => $𝘢𝘵𝘵𝘴[‘𝘤𝘰𝘶𝘯𝘵’]));
$𝘰𝘶𝘵𝘱𝘶𝘵 = ‘<𝘶𝘭>’;
𝘧𝘰𝘳𝘦𝘢𝘤𝘩 ($𝘳𝘦𝘤𝘦𝘯𝘵_𝘱𝘰𝘴𝘵𝘴 𝘢𝘴 $𝘱𝘰𝘴𝘵) {
$𝘰𝘶𝘵𝘱𝘶𝘵 .= ‘<𝘭𝘪>’ . 𝘦𝘴𝘤_𝘩𝘵𝘮𝘭($𝘱𝘰𝘴𝘵[‘𝘱𝘰𝘴𝘵_𝘵𝘪𝘵𝘭𝘦’]) . ‘</𝘭𝘪>’;
}
$𝘰𝘶𝘵𝘱𝘶𝘵 .= ‘</𝘶𝘭>’;

𝘳𝘦𝘵𝘶𝘳𝘯 $𝘰𝘶𝘵𝘱𝘶𝘵;
}
𝘢𝘥𝘥_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦(‘𝘳𝘦𝘤𝘦𝘯𝘵_𝘱𝘰𝘴𝘵𝘴’, ‘𝘳𝘦𝘤𝘦𝘯𝘵_𝘱𝘰𝘴𝘵𝘴_𝘴𝘩𝘰𝘳𝘵𝘤𝘰𝘥𝘦’);

Now, you can use [𝘳𝘦𝘤𝘦𝘯𝘵_𝘱𝘰𝘴𝘵𝘴 𝘤𝘰𝘶𝘯𝘵=”3″] to display the latest three posts, or customize it further as needed.

💡 𝗣𝗿𝗼 𝗧𝗶𝗽: Shortcodes are great for theme and plugin development, providing reusable functionality without needing to edit page templates.

hashtag#WordPress hashtag#WebDevelopment hashtag#PHP hashtag#CustomShortcodes hashtag#DynamicContent

Leave a Reply

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