There are times when you might want to use PHP directly within a post's content. You might also want to simplify the process of repeatedly writing the same text or tags.
This is where WordPress's "shortcode" feature comes in handy.
Creating them is simple! However, to prevent your shortcodes from disappearing when you update your theme, it's a good idea to create a child theme.
[WORDPRESS] How to Prevent Changes from Being Overwritten During Theme Updates
The page below uses a shortcode to display the basic app information section.
HOW TO CREATE A SHORTCODE
function hogehoge() {
return "template message etc";
}
add_shortcode('sample', 'hogehoge');The code above calls the 'hogehoge' function, which returns a simple message, using 'add_shortcode'.
Now, by writing the following in your post content, you can call the function specified by the shortcode:
[sample]CREATING SHORTCODES WITH ATTRIBUTES
By adding attributes to a shortcode, you can pass values to a function just like arguments.
//functions.php
function getAppInfo($atts = array()) {
shortcode_atts(array(
'id' => 'default',
'lang' => 'default'
), $atts);
$url = "https://itunes.apple.com/lookup?id=" . $atts['id'] . "&country=" . $atts['lang'];
return $url;
}
add_shortcode('appinfo', 'getAppInfo');
//Post
[appinfo id="102030" lang="JP"]By including attributes specified in the 'shortcode_atts' function within your shortcode, you can pass values as if they were arguments. If no attributes are passed, the default values specified within the function will be used.
When used within the function, as shown in the example above, values are stored as an array in `$atts`. You can then call and use these array values.
That concludes this simple overview of creating shortcodes.
This explanation assumes a certain level of PHP knowledge, but for instance, if you use `var_dump()` inside a function, the data will be displayed directly within the post content where the shortcode is placed. This can be very useful during development.
RECOMMENDED WORDPRESS BOOKS
While reading books is important, I truly feel that implementing things yourself leads to a deeper understanding.
I recommend reading books about WordPress itself and also about PHP.
Knowing HTML and CSS will broaden your capabilities, but a great advantage of WordPress is that you can manage the design aspects simply by relying on templates.
The Easiest WordPress Introduction Course (Japanese) Paperback
WordPress fundamentals. It provides a detailed explanation from installation onwards.
There are many books available, so any would be fine, but this one has a recent publication date and the author is beautiful.
Aimed at serious developers. It introduces practical examples, making it useful for discovering new ideas.
📦