1

So I am working on a plugin and am trying to trigger a js file whenever a post is saved. I have been reading up on this all morning and cannot seem to find why this is not working. Any advice? If I were to paste the js code directly into the plugin it seems to work... I have double checked the path to the js and still no response.

add_action( 'admin_init', 'plugin_admin_init' );
function plugin_admin_init() {  
    wp_register_script( 'qtool-insert-v2', plugins_url() . '/buildStatus2/' . 'qtool-insert-v2.js' );
}

add_action( 'save_post', 'add_my_script' );
function add_my_script() {
    wp_enqueue_script( 'qtool-insert-v2' );
}

Here is the qtool-insert-v2.js - very simple redirect.

<script type="text/javascript">
<!--
window.location = "http://www.google.com/"
//-->
alert("HELLO");
</script>

1 Answer 1

1

You need to hook into admin_enqueue_scripts with your add_my_script function.

http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts

Example:

function add_my_script() {
    wp_enqueue_script('qtool-insert-v2');
}add_action( 'admin_enqueue_scripts', 'add_my_script' );
5
  • ahh okay thanks for that advice. I am now successfully seeing it in the source. Although their is no redirect or popup happening... also, it looks like this script now loads on every admin page... any way I can only have it triggered on that save_post hook? <script type='text/javascript' src='http://....../plugins/buildStatus2/qtool-insert.js?ver=3.3.2'></script> Commented Jul 24, 2012 at 15:42
  • looks like I don't need the <script> tags... still need to figure out a way to only have this trigger on a save post tho Commented Jul 24, 2012 at 15:52
  • You can only trigger the admin_enqueue_scripts on certain admin pages, see the link above (codex.wordpress.org/Plugin_API/Action_Reference/…) Commented Jul 24, 2012 at 16:01
  • @Greg Are you trying to run JS on a save post PHP action or a save click event? Commented Jul 24, 2012 at 17:02
  • @BrianFegter on a save post action. Whenever a post is published or updated. Commented Jul 24, 2012 at 17:07

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.