The correct way to add shortcode

Here’s an example of how I handle them:

<?php

namespace App;

use App\Controllers\App;

/**
 * Return if Shortcodes already exists.
 */
if (class_exists('Shortcodes')) {
    return;
}

/**
 * Shortcodes
 */
class Shortcodes
{
    /**
     * Constructor
     */
    public function __construct()
    {
        $shortcodes = [
            'box',
            'date',
            'month',
            'day',
            'year'
        ];

        return collect($shortcodes)
            ->map(function ($shortcode) {
                return add_shortcode($shortcode, [$this, strtr($shortcode, ['-' => '_'])]);
            });
    }

    /**
     * Box
     * Wraps content in a box.
     *
     * @param  array  $atts
     * @param  string $content
     * @return string
     */
    public function box($atts, $content = null)
    {
        return '<div class="box">' . do_shortcode($content) . '</div>';
    }

    /**
     * Date
     * Returns the current date.
     *
     * @param  array  $atts
     * @param  string $content
     * @return string
     */
    public function date($atts, $content = null)
    {
        return date('F d, Y');
    }

    /**
     * Month
     * Returns the current month.
     *
     * @param  array  $atts
     * @param  string $content
     * @return string
     */
    public function month($atts, $content = null)
    {
        return date('F');
    }

    /**
    * Day
    * Returns the current day.
    *
    * @param  array  $atts
    * @param  string $content
    * @return string
    */
    public function day($atts, $content = null)
    {
        return date('d');
    }

    /**
     * Year
     * Returns the current year.
     *
     * @param  array  $atts
     * @param  string $content
     * @return string
     */
    public function year($atts, $content = null)
    {
        return date('Y');
    }
}

new Shortcodes();

This lives within’ app/shortcodes.php after adding 'shortcodes' to the required files array_map() in functions.php.

Simply create a function with the name of your shortcode (using an underscore in place of a hyphen if applicable) and return a value. Afterwards, add it to the array in the construct and it will get initiated and if an underscore is present, will be changed to a hyphen (e.g. my_shortcode would become [my-shortcode]).

9 Likes