Question

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!

Was it helpful?

Solution

Finally, 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;
} );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top