I'm creating a plugin that adds a custom button to the default TinyMCE editor in WordPress admin.

The following code builds this simple plugin


function mkay_enqueue_plugin_script( $plugin_array ){
    $plugin_array['subscriptionPlugin'] = plugin_dir_url( __FILE__ ) . 'mkay-tinymce-extra-buttons.js';
    return $plugin_array;
add_filter( 'mce_external_plugins', 'mkay_enqueue_plugin_script' );

function mkay_register_buttons_editor( $buttons ){
    array_push( $buttons, 'subscription' );
    return $buttons;
add_filter( 'mce_buttons', 'mkay_register_buttons_editor' );


tinymce.create('tinymce.plugins.subscriptionPlugin', {
    init: function(editor, url){
        editor.addButton('subscription', {
            title: 'Link per l\'iscrizione',
            cmd: 'subscriptionCmd',
            icon: false,
            text: 'Link iscrizione'

        editor.addCommand('subscriptionCmd', function(){
            var selectedContent = editor.selection.getContent();
            var box = '<a href="/iscrizione/?data_corso=[custom field value]" class="subscription-link">'+selectedContent+'</div>';
            editor.execCommand('mceInsertContent', 0, box);

tinymce.PluginManager.add('subscriptionPlugin', tinymce.plugins.subscriptionPlugin);

Till here the plugin seems to work well.

Now I need to take the value of a custom field from the post and put it in place of [custom field value] in js file. Then if possible show the custom button only if post is draft or published and the custom field is not empty.

Does someone have any idea? Any help's appreciated.

1 Answer 1


Rather than finding the custom field value when the user hits the button, change the [custom field value] to a shortcode name (perhaps "[mkay_subscription_button_value]"?) and then create a shortcode that can replace the value of that key with the post's custom meta. Something like this:

function 246286_display_custom_field( $atts ) {
    $data = get_post_meta( get_the_ID(), 'mkay_custom_field', true );
    return $data;
add_shortcode( 'mkay_subscription_button_value', '246286_display_custom_field' );

The value of doing this is: if the post's custom meta changes after the button has been pressed, the output on the page still remains valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.