Search code examples
phpwordpresspluginscontent-management-systemshortcode

Shortcode plugins for own custom cms like wordpress shortcode plugins


I have created a custom CMS for my own and a plugin system that is working as I expected.

Now I want to create plugins based on shortcodes, eg: [gallery attr1=100 attr2="string"] and [mycode title='message' color='#F00']Hello World![/mycode]

I want to handle the above mentioned shortcodes in my CMS. Functions will replace shortcodes with HTML and get & set attributes as parameters for mySQL queries or something else.

may be regular expressions will help, I am not expert in regular expressions. I would don't like to use such regular expressions if there are other smiler or good ways exist .

CMS developed using PHP and mySQL.

I have visited the wordpress developers sites and got the concepts, I have already created functions that register or set plugins, menus, theme sidebars etc.

I think this info is enough to get the point as I can just explain in this way.

thank you in advance


Solution

  • This code solved the logic

    function plugin_sortcode($contents) {
        global $SORTCODES, $DATA;
    
        foreach ($SORTCODES as $name => $fn) {
            $attr = array();
            preg_match_all("/\[" . $name . " (.*?)\]/", $contents, $matches);
            if ($matches[0]) {
    
                $code = $matches[0][0];
                if (isset($matches[1])) {
                    $attrs = $matches[1][0];
                    $attrs = explode(" ", $attrs);
                    foreach ($attrs as $values) {
                        $attrs1 = explode("=", $values);
                        $attr[$attrs1[0]] = $attrs1[1];
                    }
                }
    
                $data = $fn($attr, $DATA);
                $contents = str_replace($code, $data, $contents);
            }
        }
    
        return $contents;
    }