Fire jQuery function when post edit screen loads

You have your jQuery hooked too early. The jQuery library has not yet loaded when the load-(page) action is fired.

Use admin_print_scripts to print inline scripts. That action comes after scripts are enqueued.

Here’s your original code using admin_print_scripts:

add_action( 'admin_print_scripts', function () { 

$status = "status-started";

if($status == 'status-started'):
    ?>
    <script>
        jQuery(document).ready(function($) { 
            /* write your JavaScript code here */
            $('.btn-start').trigger('click');
            console.log('Started successfully!');
        });
    </script>

<?php 
endif;

} );

An alternative to using admin_print_scripts would be to use admin_print_footer_scripts, which is essentially the same thing, but in the footer instead of the header. Either is generally OK and whether you do it in the header or the footer is sometimes a matter of preference and sometimes a matter of necessity. So it will depend on the actual use case.

For anyone wondering why I didn’t suggest using another hook such as wp_head or wp_footer, there are two reasons. First, it’s not what those hooks were intended for. Using them would get your scripts out of sequence with where they really should be (although in a lot of cases they would work just fine). Second, they are not admin specific hooks. The question of a load-(page) action indicates this is an admin side process, so use the proper admin side hooks.

I would say similar things about the use of various “enqueue” hooks. First, don’t use an enqueue that is not admin side specific (speaking specifically of this original post and not in generalities). Second, enqueueing is for libraries and static scripts. If you’re printing out scripts (especially ones that may be dynamic), use the _print_scripts hooks instead.

Leave a Comment

tech