在用户点击按钮后运行php代码?

时间:2017-06-04 作者:Asem J Syed

目标:用户单击按钮订阅标签存档页面上的标签。

我正在使用当前代码:

            <?php
                $tag_id = get_query_var(\'tag_id\');
                $current_user = wp_get_current_user();
                $user_id = $current_user->ID;
                $currentList = $current_user->subList;
                $tag_id = get_query_var(\'tag_id\');
                $tagStr = " " . $tag_id . ",";
                $update;
                if(strpos($currentList,$tagStr)!== false) {
                    echo \'Already in list\';
                }
                else {
                    echo \'Added to list\';
                    $update = $currentList . $tagStr;
                    update_user_meta($user_id,\'subList\',$update);
                }
            ?>
subList是我在User\\u元数据库中创建的元键,用于存储用户订阅的所有标记ID。

The problem is that this code runs when the page loads, so just viewing it will make the user subscribe to it. I want it to execute on the click of a button.

1 个回复
SO网友:Johansson

您可以将代码包装在函数中,然后使用按钮激活它。创建一个按钮并为其onclick 事件:

<span onlclick="javaSubscribe();">Subscribe</span>
现在,单击按钮后向服务器发出AJAX请求:

function javaSubscribe() {
    // We need the ID for user and tag. Let\'s retrieve it from a div we will create later
    var id = getElementById(\'user-id-div\').textContent;
    var tag = getElementById(\'tag-id-div\').textContent;
    // Time for the real fun, let the call to the function begin
    jQuery.ajax({
        type: \'GET\', 
        url: \'http://example.com/wp-json/some_path_here/v1/my_subscribe?user_id=\' + id + \'&tag_id=\' + tag, 
        data: { get_param: \'value\' }, 
        dataType: \'json\',
        success: function (data) {
            if (data != null) {
                // Do whatever you want with the response
            } 
        }
    });
};
然后注册REST路由,并将代码包装到其回调函数中:

add_action( \'rest_api_init\', function () {
    //Path to ajax function
    register_rest_route( \'some_path_here/v1\', \'/my_subscribe/\', array(
            \'methods\' => \'GET\', 
            \'callback\' => \'subscribe_php\' 
    ) );
});
// The function we set in the callback
function subscribe_php(){
    // Retrieving the data from our AJAX request
    if (isset($_GET[\'user_id\'])) {
        $user_id = $_GET[\'user_id\'];
    }
    if (isset($_GET[\'tag_id\'])) {
        $tag_id = $_GET[\'tag_id\'];
    }
    $currentList = $current_user->subList;
    $tagStr = " " . $tag_id . ",";
    $update;
    if(strpos($currentList,$tagStr)!== false) {
        return \'Already in list\';
    }
    else {
        $update = $currentList . $tagStr;
        update_user_meta($user_id,\'subList\',$update);
        return \'Added to list\';
    }
}
但是您需要有人将数据传递给函数。我建议您在一个隐藏的div中输出它,然后在PHP函数中检索它。您可以在模板中使用此选项,例如:

<div id="user-id-div"><?php echo wp_get_current_user()->ID; ?></div>
<div id="tag-id-div"><?php echo get_query_var(\'tag_id\'); ?></div>
使用此方法输出所有需要的信息并将其传递给函数。

结束