How to execute a javascript function just before saving a woocommerce post or a post?

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;
    } );
} );

Leave a Comment