最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugins - Call function with button and return response

programmeradmin1浏览0评论

I'm trying to do the folllowing.

I have a button in my template (in templates folder of my plugin). When they press the button I want to call a function and send and id to the function.

In that function I want to create an api call and send the results back to the template. How can I do this?

I'm trying to do the folllowing.

I have a button in my template (in templates folder of my plugin). When they press the button I want to call a function and send and id to the function.

In that function I want to create an api call and send the results back to the template. How can I do this?

Share Improve this question asked Aug 30, 2019 at 12:05 nielsvnielsv 1731 gold badge5 silver badges17 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Based on the limited detail of your question something as per the following is a rough gist of what you could do.

In your theme functions.php file:

<?php

function handle_request () {

    if (isset($_GET['custom_id']) && isset($_GET['custom_id_nonce']) ) {


        if ( wp_verify_nonce($_GET['custom_id_nonce'], 'custom_id_action') ) {
            $id = $_GET['custom_id'];

            // FIRST
            // do something with $id

            // THEN
            // possibly redirect somewhere else or back to referrer 
            // e.g. wp_safe_redirect( wp_get_referer() );
            // see https://codex.wordpress/Function_Reference/wp_get_referer
            // see https://codex.wordpress/Function_Reference/wp_safe_redirect


        } else {
            // handle failure state, nonce value is incorrect...
        }

    }

    // if here, the request was likely not for you

}

add_action( 'init', 'handle_request' );

In your theme template file:

<a href="<?php echo wp_nonce_url( home_url('?custom-id=123'), 'custom_id_action', 'custom_id_nonce' );?>">CLICK ME</a>

In the above example, where home_url('?custom-id=123') is stated, you may want to change the basis for this URL to be the current URL the user is on.

Important reading:

  • https://codex.wordpress/WordPress_Nonces
  • https://codex.wordpress/Function_Reference/wp_nonce_url
  • https://codex.wordpress/Function_Reference/wp_get_referer
  • https://codex.wordpress/Function_Reference/wp_safe_redirect
发布评论

评论列表(0)

  1. 暂无评论