0
votes

I try too add code highlighting for blog with TinyMCE 4.3.1 capabilities. At first I don't understand why I don't have this plugin in wp-includes/js/tinymce/plugins folder after WP update, so I have to insert it manually.

I added such filter:

function mytheme_tinymce_settings( $settings ) {
    $settings['plugins'] .= ",codesample";
    $settings['toolbar1'] .= ",codesample";

    return $settings;
}
add_filter( 'tiny_mce_before_init', 'mytheme_tinymce_settings' );

So now I have button to add code snippets and it highlighted well in editor field, but when I publish post simple pre appears. When I add filter than /wp-includes/js/tinymce/plugins/codesample/plugin.min.js?wp-mce-4310-20160418 appears in both pages: edit page and post view page, but works only for edit page.

How to make it work on post view page?

2

2 Answers

0
votes

The codesample plugin relies on Prism.js (and a CSS file) to handle the syntax highlighting in TinyMCE. This is documented here:

https://www.tinymce.com/docs/plugins/codesample/

You likely just need to add Prism.js and Prism.css to your rendered page to get the highlighting. This is documented here:

https://www.tinymce.com/docs/plugins/codesample/#usingprismjsonyourwebpage

0
votes

Solution:

function mytheme_tinymce_settings( $settings ) {
    $settings['plugins'] .= ",codesample";
    $settings['toolbar1'] .= ",codesample";

    return $settings;
}
add_filter( 'tiny_mce_before_init', 'mytheme_tinymce_settings' );

Adds button in tinyMCE.

wp_enqueue_style('prism','/wp-includes/js/tinymce/plugins/codesample/css/prism.css');
wp_enqueue_script('prism_js',plugins_url( 'js/run_code_highlighting.js', __FILE__ ), array('jquery')); 

Adds js and css files on page(I created small plugin for this).

jQuery(window).load( function() {
    tinymce.codesampleplugin.Prism.highlightAll();
});

Run prism highlighting for all elements on page (document ready doesn't work - tinymce.codesampleplugin is null at this moment).

P.S. Can be a little bit tricky to add highlighting in comments if you don't refresh page after comment update for example.