1

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.

3

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.

  • In other words - to be able to have the access also while creating new page/post - I would need to hook into autosave feature, get the ID from there and add to global variable? Is it even possible? – Marcin Bobowski Nov 4 '13 at 6:47
  • Exactly. I'm not sure what the time limit is before autosave; but you could force a wp_insert_post() via an ajax call anytime a new post/page is added. But this could result in many unneeded posts and pages. Alternatively, you could check for the existence of the ID from your tinymce script.. and alert the post needs to be saved first if it does not yet exist. – josh Nov 4 '13 at 11:49
  • hmm it seems that post_id is available just after opening new post or new page - the ID is assigned right away and is available. – Marcin Bobowski Nov 4 '13 at 16:34
  • Well; that's good to know. I will edit my answer above. So is it working properly for you? – josh Nov 4 '13 at 19:08
  • Yes, in 3.7 for sure :) – Marcin Bobowski Nov 5 '13 at 14:58
2

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

    var post_id = jQuery('#post_ID').val();
  • Much better, more elegant solution. This should be updated to be the correct answer. – edwardr Jul 25 '17 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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