Your code depends on the post being in an auto-draft
state immediately before publication, which isn’t guaranteed. For a more generic option, try using the transition_post_status
hook:
function display_console_log( $new_status, $old_status, $post ) {
// Only runs if the post is transitioning from a not-published state
// to the `publish` state.
if ( 'publish' !== $old_status && 'publish' === $new_status ) {
echo "
<script>
console.log('New post published')
</script>
";
}
}
add_action( 'transition_post_status', 'display_console_log', 10, 3 );
(Also, tangentially related, it’s not in keeping with the WordPress Way to inject JavaScript code directly; I recommend reading up on how and why to use wp_enqueue_script()
.)