wp-shortcake / shortcake

Shortcake makes using WordPress shortcodes a piece of cake.
GNU General Public License v2.0
665 stars 143 forks source link

Adds `shortcode_ui_preview` filter #769

Open joseadrian opened 6 years ago

joseadrian commented 6 years ago

Added shortcode_ui_preview filter to give the option to modify the preview in the WYSIWYG.

Some people want to have the option not to preview the content parsed in the editor because they might break the content, or use the dashicons instead.

The filter added will allow them to do that:

// $options = Shortcode UI Options
add_filter('shortcode_ui_preview', function($return, $shortcode_tag, $shortcode, $options) { 
    if($shortcode_tag == 'special_shortcode_tag') {
         return '<img src="/path/to/image">';
    }

    return sprintf( '<span class="dashicons %s"></span> %s', $options['listItemImage'], $options['label']);
}, 10, 4);
davisshaver commented 6 years ago

Hi @joseadrian, thanks for contributing. The filter seems reasonable to me. I'm a little suspicious of the new regex in there though. Would you be willing to move that into a utility function and add some test coverage to make sure it handles different shortcode configurations as you expect? Here's the chunk of code I'm looking at.

+       preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $shortcode, $matches );
+       $shortcode_tag = isset( $matches[1][0] ) ? $matches[1][0] : '';
goldenapples commented 6 years ago

I was actually wondering if there wasn't a simpler way of doing this. We've talked about a few options that might work:

  1. Adding an argument to the shortcode_ui_register_for_shortcode args, like 'preview' => false, and, if that option is set, just showing the text of the shortcode in an mce view, rather than rendering the preview.
  2. Using the SHORTCODE_UI_DOING_PREVIEW constant to return an alternate rendition of a shortcode when rendering a shortcode preview for the editor. (This is already possible, by filtering pre_do_shortcode_tag or do_shortcode_tag and checking for the value of the SHORTCODE_UI_DOING_PREVIEW constant. But we could probably expose a utility method to make it easier.)

Would either, or a combination of these approaches fit your use case as well?