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

In this tutorial we’ll learn how to execute a javascript function just before creating/saving a woocommerce product.

To do this add the following lines of code at the end of your functions.php file.

functionadmin_queue( $hook ) {

global $post;

 

if ( $hook == 'post-new.php' || $hook == 'post.php' ) {

if ( 'product' === $post->post_type ) {

wp_enqueue_script( 'custom', bloginfo( 'template_directory' ) . '/wp-content/themes/twentyfourteen/js/custom.js', 'jquery', '', true );

       }

   }

}

add_action( 'admin_enqueue_scripts', 'admin_queue' );

You can access functions.php file here:

woocommerceThis will add a new javascript file into the site where we’ll our code.

Now create a new file in the directory mentioned in the function named custom.js which is in our case:

http://localhost/wordpress/wp-content/themes/twentyfourteen/custom.js

You’ll replace this with your directory and will create the file accordingly.

Now open the javascript file you just created and add the following js code in the file:

// JavaScript Document

jQuery( document ).ready( function($){

   $( '#publish' ).click(function(){

alert( 'Hello World!' );

return false;

   });

});

After placing code save the file. You can write your own code which you want to execute with the “alert(‘hello world’);”

Now, if you’ll go to create product page and try to create the product by clicking on “publish” button your js code will get executed.

woocommerce

 

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

Leave a Comment

Your email address will not be published. Required fields are marked *