如何在WordPress中调用href上的PHP函数?

问题描述 投票:4回答:3

我有以下功能。我想在用户点击超链接(取消激活我的帐户)时调用此功能。在href点击上调用函数的最佳方法是什么?谢谢

function deleteUserMeta($userID) {
    delete_usermeta($userID, 'subscription_id');
    delete_usermeta($userID, 'ref_id');
    delete_usermeta($userID, 'users_name');
    delete_usermeta($userID, 'trans_key');
}
wordpress
3个回答
10
投票

正如Thorben所提到的,你不能在浏览器事件上执行PHP函数,因为语言是服务器端而不是客户端。但是,有几种方法可以解决这个问题:

1.服务器端(PHP)

你不能在浏览器事件上调用PHP函数(例如链接点击),但你可以在点击超链接时加载的页面上调用它 - 让我们称之为'next.php'。要做到这一点,请在'next.php'的最顶部有条件地调用你的函数deleteUserMeta()。问题是您需要将一些变量传递给此页面,以便您可以检查条件并执行该功能。使用GET通过超链接传递变量,如下所示:

<a href="next.php?unsubscribe=true&userID=343">Unsubscribe</a>

您希望如何传递userId取决于您。在上面的示例中,它是硬编码的,但您也可能以某种方式使用PHP设置它,如下所示:

<a href="next.php?unsubscribe=true&userID=<?php echo $userID;?>">Unsubscribe</a>

现在在'next.php'上,使用条件来评估该变量:

<?php
if($_REQUEST['unsubscribe'] == 'true'){
    deleteUserMeta($_REQUEST['userID']);
}
?>

2.客户端(AJAX)

执行此操作的另一种方法是使用某些AJAX在客户端执行此操作。如果您不熟悉Javascript / jQuery / AJAX,我可能会坚持使用其他解决方案,因为它可能更容易实现。如果你已经使用了jQuery,这应该不会太难。使用jQuery,您可以将此函数绑定到超链接的实际单击事件。这样,整个操作可以在不刷新页面的情况下发生:

<a href="#" onclick="ajaxDeleteUserMeta()">Unsubscribe/a>

现在你需要两件事:1。第一个解决方案所需的同一个PHP文件“next.php”只包含对你的函数的调用,deleteUserMeta($userId) 2.一个名为ajaxDeleteUserMeta()的javascript函数,所以在你的JS中创建一个这个:(因为这是一个命名函数,它不需要像大多数匿名jQuery函数那样进入jQuery(document).ready(function(){});。)

function ajaxDeleteUserMeta(){

var userID = ''; // fill this in to somehow acquire the userID client-side...

jQuery.ajax({
   type: "POST",
   url: "next.php", /* this will make an ajax request to next.php, which contains the call to your original delete function. Essentially, this ajax call will hit your original server-side function from the client-side.*/
   data: "userID="+userID+"&unsubscribe=true", /*here you can pass a POST variable to next.php that will be interpreted by the conditional function.*/
   success: function(msg){
     alert( "Data Saved: User ID " + userID + " deleted." );
   }

});

}

啰嗦,但我希望其中一些有点意义。


1
投票

这是PHP代码?您无法直接从浏览器调用PHP函数。您可以尝试将GET或POST变量附加到您的请求中,在PHP中读取它,然后最终执行上述函数。


1
投票

您可以使用ajax对刚刚调用该方法的URL进行发布。

使用jQuery的示例: onclick="$.post('http://yourdomain/delete_user?userid',callBackFunction());" 然后在你的php中将该url映射到你的php函数。我从来没有使用PHP或wordpress所以我不知道你是怎么做的,但它应该是直截了当的,因为它是一个常见的情况。

© www.soinside.com 2019 - 2024. All rights reserved.