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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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.

Method 2

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

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x