I am trying to add javascript when a post has been published so that it’s more noticable for my user but I can’t figure out what to use.
I tryed with publish_post and save_post, but it doesn’t work unless I put die; at the end of the code.
I’ve tryed so hard to stay out of the wordpress core code, and I really don’t want to have to because of this problem…
here’s my code :
function run_when_post_published($post_ID){
echo '<script type="text/javascript">
alert("essai");
</script>';
}
add_action('publish_slider', 'run_when_post_published');
Thanks for your help !
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 withwp_localise_script
. What this means is the value ofmessage
will be available in our javascript file as a property of the global objectwpsePost
(in particularwpsePost.message
). You can then do whatever according to its value.Then create the
notice.js
:Here is an example of how you can have custom message for custom post_type ‘book’. Note the array index 6 “Book Published”.
You might be able to use the same hook to echo your JavaScript message, but I would not recommend doing it.
add_filter('admin_head', 'my_custom_alert')
Then add the custom alert by getting the query var which wordpress adds to the query string when a page has been saved
function my_custom_alert(){