Using post ID in custom tinyMCE button

I’m building a simple plugin and need to be able to access current post id when user clicks custom tinyMCE button (inside its onclick function). How should I get current post ID to do that.

Just for this example, code from this tutorial:
http://brettterpstra.com/2010/04/17/adding-a-tinymce-button/
can be used, and after clicking on the button, current post id could be logged into console (console.log) or alerted to screen.

Related posts

2 comments

  1. You would need to place a globally namespaced javascript variable in your php code where you enqueue the script to be loaded for the editor pages.

    So, this code will enqueue a script function to be added to the “edit post/page” screens:

    add_action('admin_head','my_add_styles_admin');
    function my_add_styles_admin() {
    
        global $current_screen;
        $type = $current_screen->post_type;
    
        if (is_admin() && $type == 'post' || $type == 'page') {
            ?>
            <script type="text/javascript">
            var post_id = '<?php global $post; echo $post->ID; ?>';
            </script>
            <?php
        }
    }
    

    Now, in your editor_plugin.js file for your tinymce button; you can access this post ID by simply calling the post_id javascript variable.

  2. I found a simpler solution, maybe someone can use it:

        var post_id = jQuery('#post_ID').val();
    

Comments are closed.