Running a php code after User clicks a button? [closed]

You can wrap your code in a function and use a button to activate it. Create a button and assign a function to it’s onclick event:

<span onlclick="javaSubscribe();">Subscribe</span>

Now, make an AJAX request to your server after clicking the button:

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
            } 
        }
    });
};

Then register a REST route and wrap your code in it’s callback function:

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';
    }
}

But you will someone need to pass the data to the function. I would suggest you output it in a hidden div, and then retrieve it in your PHP function. You can use this in your template, for example:

<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>

Use this method to output all the needed information and pass it to your function.