0

I have this link from a CPT, to clone a post, in this case post=30808:

https://domain.com/wp-admin/admin.php?action=duplicate_post_clone&post=30808&_wpnonce=240f0078e7

Now, I need to use this within a jquery script like this:


    $('body.post-type-pessoas .page-title-action').replaceWith( '<a href="https://domain.com/wp-admin/admin.php?action=duplicate_post_clone&post=30808&_wpnonce=240f0078e7" class="page-title-action">Clonar Modelo PESSOA</a>' );
});

(this will replace the "New Post" button with "Clonar Modelo PESSOA" with the same link)

The thing is that after several days the link won't work because of the wpsnonce lifetime. I don't want to remove the wpsnonce lifetime due to security issues.

My question is how do I get the correct and actualized link?

Thank you.

AMP.

1 Answer 1

2

One option is to use wp_add_inline_script() to inline the action url to the page source. This can be done for example on the admin_enqueue_scripts action.

In the example below I used admin_url() with wp_nonce_url() to retrieve the nonce wp-admin url and then added the query paramters to it with add_query_arg().

add_action( 'admin_enqueue_scripts', 'my_admin_action_url', 5 );
function my_admin_action_url() {
    $actionUrl = add_query_arg([
        'action' => 'duplicate_post_clone',
        'post' => 30808,
    ], wp_nonce_url( admin_url('admin.php'), 'action' ));

   wp_add_inline_script( 'jquery', "var myAdminActionUrl = '{$actionUrl}';" );
}

The url should be now available in your script via the myAdminActionUrl variable.

5
  • Thank you Antti. But could you please let me know how do I use that var myAdminActionUrl within my jquery .js file?
    – Horacsio
    Commented Jul 13, 2022 at 19:49
  • @Horacsio The same way you would use any other variable, e.g. alert(myAdminActionUrl); The variable is in the global scope so it is available to any script. Commented Jul 14, 2022 at 10:16
  • Thank you for your precious help here. To conclude I've used the jquery var like this: .replaceWith( '<a href="' + myAdminActionUrl + '">link text</a>' );
    – Horacsio
    Commented Jul 18, 2022 at 11:07
  • for some reason the wpnonce changes but it results in an expired link! I found with certain users it links to "wp-admin/admin.php?_wpnonce=5c08124c43&action=duplicate_post_clone&post=30808" and mine to "wp-admin/admin.php?action=duplicate_post_clone&post=30808&_wpnonce=4d19a11d48". Why?
    – Horacsio
    Commented Jul 19, 2022 at 18:56
  • @Horacsio That is rather strange. The expiration might be caused by a failed nonce check, wordpress.stackexchange.com/questions/302138/…. You'll need to check the nonce (and action) naming and handling so that there aren't any issues. Commented Jul 19, 2022 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.