Add javascript when post is published

To enqueue scripts on the admin side, you should use the admin_enqueue_scripts hook. In this callback I check that are on the appropriate page (i.e. the page where you edit posts / post types), using the passed $hook argument.

Optionally you can check if the post is of a specific type (in case this is only for posts, pages, or a cpt).

Finally we’ll borrow WordPress’ in-built notice system. This produces the ?message=1. The value 1-10 determines the notice message. (See @Azizur’s answer for this relationship).

In this example, we only enqueue our javascript if the message variable is set.

We then enqueue our script, (which I’ve assumed is located: [theme-folder]/js/notice.js (alternatively point this to your plug-in folder). Then we ‘localise’ it with wp_localise_script. What this means is the value of message will be available in our javascript file as a property of the global object wpsePost (in particular wpsePost.message). You can then do whatever according to its value.

add_action( 'admin_enqueue_scripts', 'wpse50770_add_admin_scripts', 10, 1 );
function wpse50770_add_admin_scripts( $hook ) {
    global $post;

    //Only need to enque script on the post.php page
    //Optional: restirct by post type
    if ( 'post.php' == $hook  && 'post' == $post->post_type && isset($_GET['message']) ) {     
        $message_id = absint( $_GET['message'] );
        wp_enqueue_script(
            'wpse-notice',
            get_template_directory_uri() . '/js/notice.js',
            array('jquery')
        );
        $data = array( 'Message' => $message_id);
        wp_localize_script( 'wpse-notice', 'wpsePost', $data );
    }
}

Then create the notice.js:

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

    if( wpsePost.Message == 6 ){
        alert('Post published');

    }else if( wpsePost.Message == 1 ){
        alert('Post updated');
    }

});

Leave a Comment

deneme bonusu veren sitelerbahis casinomakrobetceltabetpinbahispolobetpolobet girişpinbahis girişmakrobet girişpulibet girişmobilbahis girişkolaybet giriş