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
1 Answer
Reset to default 0Your 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
版权声明:本文标题:plugins - Executing Javascript when a New Post is Published 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745295916a2652076.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论