Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active February 21, 2024 21:36
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save igorbenic/f63f1d21823871833d937e06c05ee8a0 to your computer and use it in GitHub Desktop.
Save igorbenic/f63f1d21823871833d937e06c05ee8a0 to your computer and use it in GitHub Desktop.
How to use the WordPress Code Editor in your Plugins or Themes | https://www.ibenic.com/wordpress-code-editor
<?php
add_action( 'add_meta_boxes', 'add_page_scripts' );
/**
* Register the metabox
*/
function add_page_scripts() {
add_meta_box( 'page-scripts', __( 'Page Scripts & Styles', 'textdomain' ), 'add_page_metabox_scripts_html', 'page', 'advanced' );
}
'use strict';
(function($){
$(function(){
if( $('#code_editor_page_head').length ) {
var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
editorSettings.codemirror = _.extend(
{},
editorSettings.codemirror,
{
indentUnit: 2,
tabSize: 2
}
);
var editor = wp.codeEditor.initialize( $('#code_editor_page_head'), editorSettings );
}
if( $('#code_editor_page_js').length ) {
var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
editorSettings.codemirror = _.extend(
{},
editorSettings.codemirror,
{
indentUnit: 2,
tabSize: 2,
mode: 'javascript',
}
);
var editor = wp.codeEditor.initialize( $('#code_editor_page_js'), editorSettings );
}
if( $('#code_editor_page_css').length ) {
var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
editorSettings.codemirror = _.extend(
{},
editorSettings.codemirror,
{
indentUnit: 2,
tabSize: 2,
mode: 'css',
}
);
var editor = wp.codeEditor.initialize( $('#code_editor_page_css'), editorSettings );
}
});
})(jQuery);
<?php
add_action( 'admin_enqueue_scripts', 'add_page_scripts_enqueue_script' );
/**
* Enqueue the Code Editor and JS
*
* @param string $hook
*/
function add_page_scripts_enqueue_script( $hook ) {
global $post;
if ( ! $post ) { return; }
if ( ! 'page' === $post->post_type ) { return; }
if( 'post.php' === $hook || 'post-new.php' === $hook ) {
wp_enqueue_code_editor( array( 'type' => 'text/html' ) );
wp_enqueue_script( 'js-code-editor', plugin_dir_url( __FILE__ ) . '/code-editor.js', array( 'jquery' ), '', true );
}
}
<?php
/**
* Meta box display callback.
*
* @param WP_Post $post Current post object.
*/
function add_page_metabox_scripts_html( $post ) {
$post_id = $post->ID;
$page_scripts = get_post_meta( $post_id, 'page_scripts', true );
if ( ! $page_scripts ) {
$page_scripts = array(
'page_head' => '',
'js' => '',
'css' => '',
);
}
?>
<fieldset>
<h3>Head Scripts</h3>
<p class="description">Enter scripts and style with the tags such as <code>&lt;script&gt;</code></p>
<textarea id="code_editor_page_head" rows="5" name="page_scripts[page_head]" class="widefat textarea"><?php echo wp_unslash( $page_scripts['page_head'] ); ?></textarea>
</fieldset>
<fieldset>
<h3>Only JavaScript</h3>
<p class="description">Just write javascript.</p>
<textarea id="code_editor_page_js" rows="5" name="page_scripts[js]" class="widefat textarea"><?php echo wp_unslash( $page_scripts['js'] ); ?></textarea>
</fieldset>
<fieldset>
<h3>Only CSS</h3>
<p class="description">Do your CSS magic</p>
<textarea id="code_editor_page_css" rows="5" name="page_scripts[css]" class="widefat textarea"><?php echo wp_unslash( $page_scripts['css'] ); ?></textarea>
</fieldset>
<?php
}
<?php
/**
* Plugin Name: Using Core Code Highlight
* Description: How to use the Core Code Highlighter in Plugins/Themes
* Version: 10
*/
if ( ! defined( 'ABSPATH' ) ) { return; }
<?php
/**
* Save meta box content.
*
* @param int $post_id Post ID
*/
function page_scripts_save_meta_box( $post_id ) {
if( defined( 'DOING_AJAX' ) ) {
return;
}
if( isset( $_POST['page_scripts'] ) ) {
$scripts = $_POST['page_scripts'];
update_post_meta( $post_id, 'page_scripts', $scripts );
}
}
add_action( 'save_post', 'page_scripts_save_meta_box' );
<?php
add_action( 'wp_head', 'page_scripts_add_head' );
/**
* Put scripts in the head.
*/
function page_scripts_add_head() {
$post_id = get_the_id();
$page_scripts = get_post_meta( $post_id, 'page_scripts', true );
if ( ! $page_scripts ) { return; }
if ( isset( $page_scripts['page_head'] ) && '' !== $page_scripts['page_head'] ) {
echo wp_unslash( $page_scripts['page_head'] );
}
if ( isset( $page_scripts['js'] ) && '' !== $page_scripts['js'] ) {
echo '<script>' . wp_unslash( $page_scripts['js'] ) . '</script>';
}
if ( isset( $page_scripts['css'] ) && '' !== $page_scripts['css'] ) {
echo '<style>' . wp_unslash( $page_scripts['css'] ) . '</style>';
}
}
@smileBeda
Copy link

This won't work at all because the instances are implemented 3 times with the same var names and the content of CodeMirror is not passed to textarea.

It will result in the content of CodeMirror not updating the related TextAreas when typing and hence content not saved when submitted.

Instead, a unique var name should be used for each instance and the CodeMirror content should be passed to the TextArea on keyup like so:

if( $('#code_editor_page_head').length ) {
            var cm_editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
            cm_editorSettings.codemirror = _.extend(
                {},
                cm_editorSettings.codemirror,
                {
                    lineNumbers: true,
	                indentUnit: 2,
	                tabSize: 2,
                }
            );
            var cm_editor = wp.codeEditor.initialize( $('#code_editor_page_head'), cm_editorSettings );
            $(document).on('keyup', '.CodeMirror-code', function(){
            	cm_editor.codemirror.save();
		      	$('#code_editor_page_head').html(cm_editor.codemirror.getValue());
	            $('#code_editor_page_head').trigger('change');
	        });
        }

Hope this helps anyone stumbling over the tutorial which is helpful per se but will not produce the desired results.

Thanks for it, it helped anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment