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