Add_shortcode as a Class to pass arguments to a function

To create multiple shortcodes, you can get the default values from a static attribut of the class.
This code create 2 shortcodes myshortcode1 and myshortcode2. In the included files, you can read variables $_atts, $content and $tag

class MyLittleClass {

    public static $shortcodes;


    public static function init() {

        self::$shortcodes = [
            "myshortcode1" => [
                "defaultValues" => [
                    "text" => "my link",
                    "url" => home_url("https://wordpress.stackexchange.com/"),
                ],
            ],
            "myshortcode2" => [
                "defaultValues" => [
                    "color" => "#EEC",
                ],
            ],
        ];


        foreach (array_keys(self::$shortcodes) as $code) {
            add_shortcode($code, [__CLASS__, "exe_short"]);
        }

    }

    public static function exe_short($attr, $content, $tag) {

        $atributos = self::$shortcodes[$tag]["defaultValues"];
        $_atts = shortcode_atts($atributos, $attr, $tag);

        ob_start(); 
        include(ABS_DIR . '/includes/dynamics/'.$tag.'/index.php');  
        $content = ob_get_clean();

        return $content;

    }

}

MyLittleClass::init();

you can also create shortcodes in passing an array at init or creating a filter when initializing $shortcodes.

Leave a Comment