admin管理员组

文章数量:1418627

I thought it was simple, but I can’t do it. I’ve been totally stuck for five days

I want to be able to trigger the Javascript console.log() function when a new post is published

function display_console_log() {
    echo "
        <script>
            console.log('New post published')
        </script>
    ";
}
add_action('auto-draft_to_publish', 'display_console_log');

I don’t understand what’s wrong with this code

Thank you in advance to those who will help me

I thought it was simple, but I can’t do it. I’ve been totally stuck for five days

I want to be able to trigger the Javascript console.log() function when a new post is published

function display_console_log() {
    echo "
        <script>
            console.log('New post published')
        </script>
    ";
}
add_action('auto-draft_to_publish', 'display_console_log');

I don’t understand what’s wrong with this code

Thank you in advance to those who will help me

Share Improve this question asked Jul 25, 2019 at 14:56 ernieernie 132 bronze badges 2
  • Is this before a post get published or after? – Howdy_McGee Commented Jul 25, 2019 at 15:02
  • If I understand the meaning of 'auto-draft_to_publish', the console.log() function should be triggered after the post is published – ernie Commented Jul 25, 2019 at 15:13
Add a comment  | 

1 Answer 1

Reset to default 0

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().)

本文标签: pluginsExecuting Javascript when a New Post is Published