The question:
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.
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
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