The Javascript you have will never run because WordPress is running this in the background as purely PHP, there is HTML to associate with your Javascript. If we look at the documentation on the pre_post_update
hook it states:
Called just before $wpdb->update()
Which is run purely in PHP. If it's easier to see what I mean, here's the full code on Trac, if you scroll the top top you'll notice there's no HTML Document associated to it. I believe what you need is what @Brad Dalton suggested and to create your own script and enqueue it on your post-type ( which if dealing with WooCommerce would be product
).
For example, we can add this to our functions.php
file:
/** Admin Enqueue **/
function admin_queue( $hook ) {
global $post;
if ( $hook == 'post-new.php' || $hook == 'post.php' ) {
if ( 'product' === $post->post_type ) {
wp_enqueue_script( 'custom-title-here', get_bloginfo( 'template_directory' ) . '/scripts/custom-script.js', 'jquery', '', true );
}
}
}
add_action( 'admin_enqueue_scripts', 'admin_queue' );
For more information on how to use wp_enqueue_script
, View Codex. Depending on what you're trying to do you could run your JS on the submission of the form:
jQuery( document ).ready( function( $ ) {
$( '#post' ).submit( function( e ) {
alert( 'Stopping Form From Submitting.' );
return false;
} );
} );
javascript
inside a php function and expect it to run. Javascript happens in browser, and should be triggered by some user-related event (think clicks, browsing, scrolling, etc). Php happens server side. You need to use php in that function.admin_head
or the likes, it just needs to be escaped properly with ending PHP tags?> <script> alert( 'here' ); </script> <?php
( or even echoed out really ). That being said, since this hook does run behind the scenes you would never see the alert.save_post
the JS is useless because it's being run behind the scenes, but JS could useful in other PHP functions such asadmin_head
oradmin_footer
. You may want to do this just for testing purposes ( versus creating a separate script file then enqueueing it ) or maybe it's such a small piece of code that it doesn't necessarily need it's own script ( initializing a datepicker to a css class ). I'm not suggesting it's a good practice to get into I just wanted correct the statement that it can't be done inside a PHP function.