WordPress.org

Ready to get started?Download WordPress

Forums

Suggestion for all plugin developers using shortcodes (2 posts)

  1. Mike Walker
    Member
    Posted 6 years ago #

    I am the author of the WordPress plugin AZIndex which uses shortcodes for displaying alphabetical indexes on pages and posts.

    Of course, when writing the plugin's documentation on my blog, I wanted to display an example of my shortcode. Boy wasn't that a pain! When editing, if I stayed in HTML mode I could escape the [ and ] characters but as soon as I forgot and went back into Visual mode, indexes would start popping up all over the place in my posts since my plugin would keep finding valid shortcodes in my documentation!

    So, I finally decided I had to fix this once and for all. And the answer is really quite easy, and I suggest that other plugin developers who use shortcodes do something similar. Basically, all you have to do is add an "escape" parameter to your shortcode filter:

    add_shortcode('az-index', 'az_insert_index');
    
    function az_insert_index($params) {
        extract(shortcode_atts(array('id' => 0, <strong>'escape' => 'false'</strong>), $params));
        if (<strong>$escape != 'true'</strong>) {
            $content = az_get_index_content($id);
        } else {
            // We just want to display the shortcode itself, not a substitution.
            $content = '[az-index id="'.$id.'"]';
        }
        return $content;
    }

    So with the above code, when I just want to display the shortcode itself on my blog and not an index then instead of:

    [az-index id="1"]

    which AZIndex will attempt to convert to an index, I can put:

    [az-index id="1" escape="true"]

    which will correctly display [az-index id="1"] in my post instead of an index.

    If you write any sort of documentation for your plugin that appears on your blog, adding an escape parameter to your shortcode could save you a fair amount of aggravation!

  2. Mike Walker
    Member
    Posted 6 years ago #

    Oops, this was my first post with source code in it. Didn't realize there is no HTML allowed! Here is the code again, without the errant HTML this time:

    add_shortcode('az-index', 'az_insert_index');
    
    function az_insert_index($params) {
        extract(shortcode_atts(array('id' => 0, 'escape' => 'false'), $params));
        if ($escape != 'true') {
            $content = az_get_index_content($id);
        } else {
            // We just want to display the shortcode itself, not a substitution.
            $content = '[az-index id="'.$id.'"]';
        }
        return $content;
    }

Topic Closed

This topic has been closed to new replies.

About this Topic