When a post gets published/updated, a message will be displayed which gives the permalink. Yes we can copy the permalink to clipboard manually, but I want it to be copied automatically, just like it shows the message.
My plan is, enqueue my custom javascript file on save_post action.
1. First, test if the script will run successfully.
function ff_load_scripts() {
wp_enqueue_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', false);
}
add_action('admin_enqueue_scripts', 'ff_load_scripts');
The custom.js
is just an alert():
alert("Yes it run.");
Yes, it can alert successfully.
2. Second, hook it to the 'save_post
' action.
function ff_load_scripts() {
wp_enqueue_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', false);
}
function ff_copy_permalink() {
add_action('admin_enqueue_scripts', 'ff_load_scripts');
}
add_action('save_past', 'ff_copy_permalink');
However, it doesn't run.
Please advise, thanks in advance!
When a post gets published/updated, a message will be displayed which gives the permalink. Yes we can copy the permalink to clipboard manually, but I want it to be copied automatically, just like it shows the message.
My plan is, enqueue my custom javascript file on save_post action.
1. First, test if the script will run successfully.
function ff_load_scripts() {
wp_enqueue_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', false);
}
add_action('admin_enqueue_scripts', 'ff_load_scripts');
The custom.js
is just an alert():
alert("Yes it run.");
Yes, it can alert successfully.
2. Second, hook it to the 'save_post
' action.
function ff_load_scripts() {
wp_enqueue_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', false);
}
function ff_copy_permalink() {
add_action('admin_enqueue_scripts', 'ff_load_scripts');
}
add_action('save_past', 'ff_copy_permalink');
However, it doesn't run.
Please advise, thanks in advance!
Share Improve this question edited Jun 1, 2020 at 0:15 Fofen asked May 30, 2020 at 9:44 FofenFofen 12 bronze badges 2 |1 Answer
Reset to default 0Finally, I did it! Use the post_updated_messages
hook instead.
add_filter( 'post_updated_messages', function( $messages )
{
// Get the permalink
$link = esc_url( get_permalink($post_ID) );
// Copy the permalink automatically
$autocopy = '<script type="text/javascript">navigator.clipboard.writeText("%s");</script>';
// `6` is for publishing
$messages['post'][6] = sprintf( __('Post published. <a href="%s">View post</a>'. $autocopy), $link, $link);
// `1` is for updating
$messages['post'][1] = sprintf( __('Post updated. <a href="%s">View post</a>'. $autocopy), $link, $link);
return $messages;
} );
save_post
happens in the server, often in the background. You can’t run JS when it occurs. – Jacob Peattie Commented May 30, 2020 at 10:21Post updated. View Post
shows up, it's ll be a nice place to add the JS I think, but I haven't found the way yet... – Fofen Commented May 30, 2020 at 23:48