[WORDPRESS]How to create and use a new shortcode

You may want to use PHP in the body of a post.In addition, I think that there are times when I want to simplify the place where I write the same sentence and tags every time.
That's where WordPress's "shortcode" feature plays an active part.
It's easy to create!However, let's create a child theme so that the shortcode that you made with great pains when you update the theme does not disappear.

[WORDPRESS]Prevent changes from being overwritten when updating themes

The following page uses shortcode to display the basic information part of the app.

How to make a shortcode

The following is described in function.php.

function hogehoge() {
    return "template message etc";
add_shortcode('sample', 'hogehoge');

The above calls the function hogehoge , which returns simple messages, in add_shortcode.
You can now call the function specified in the shortcode by writing the following in the post body.


Create a shortcode with attributes

By giving an attribute to the shortcode, you can pass a value to the function like an argument.

function getAppInfo($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');

[appinfo id="102030" lang="US"]

You can pass a value as if it were an argument by listing the attributes specified in the function shortcode_atts in the shortcode.If the attribute is not passed, the value specified in the function is used as is.
In the above example, it is "default".
When used in a function, it is stored as an array in $atts in the above example.Call and use the value of the array.

That's easy, but I've summarized the creation of shortcodes.
I talked on the assumption that I have some knowledge of PHP, but if I var_dump () in a function, for example, the data is displayed in the text containing the short code.It is convenient during development.