Wordpress-点击按钮执行PHP函数



我有一个名为revokeCard((的自定义函数,它可以撤销当前查看的可收藏卡(可以获得其副本(,并将积分奖励给当前用户,从而创建一个模拟用户"出售"卡的动作。

注意:卡片是使用Wordpress插件Gamipress添加的成就类型(自定义帖子类型(。

首先是功能:

function revokeCard(){

$achievement_id = get_the_ID();
$user = get_current_user_id();
$points = 1000;
$points_type = 'fan-point';
gamipress_revoke_achievement_to_user($achievement_id, $user);                     
gamipress_award_points_to_user( $user->ID, $points, $points_type ); 
}

该功能实际上是有效的,但我希望它在用户单击这些卡的单个模板上的"出售卡"按钮时运行。我确实尝试过这个代码,它是从网上发现的另一个片段修改而来的:

<form method="post">
<input type="submit" name="revoke" id="revoke" value="Sell Card" /><br/>
</form>
<?php
function revokeCurrent()
{
revokeCard();
}
if(array_key_exists('revoke',$_POST)){
revokeCurrent();
}
?>

从技术上讲,这是可行的。按下按钮后页面会立即刷新,我对此很满意,因为我希望用户看到这张卡的新计数以及他们的新积分余额。然而,它刷新得太快了,更新后的值没有显示出来。但如果我回到帖子中,我可以看到该功能已经起作用,用户已经获得了积分,并被吊销了1张卡。如果我在浏览器中单击"刷新",我还会收到一个警告,即表单数据将被重新提交,这意味着它们每次刷新时都会继续无意中丢失卡/接收点,我希望防止这种情况发生。因此,如果可能的话,我更喜欢使用按钮元素而不是表单。

我看到的所有与按钮而非表单相关的方法都建议使用ajax,但我确实想刷新页面,所以我不知道是否一定需要使用ajax。

无论哪种方法是最好的,我都非常感谢在实现此功能方面提供的任何帮助。

非常感谢。

感谢您的输入。我设法通过添加一个header(location(参数来解决这个问题,同时还添加了一个状态=已售出的查询参数,以便在卡售出时可以呈现自定义消息。完整代码如下:

<?php 
$achievement_id = get_the_ID();
$sale_price=get_field('card_sale_price');
$earned = gamipress_has_user_earned_achievement( get_the_ID(), $user_id ); ?>
<?php if($earned): ?>
<form method="post">
<input type="submit" name="revoke" id="revoke" value="Sell Card" /><br/>
</form>
<?php endif; ?>
<?php
function revokeCurrent()
{
revokeCard();
}
if(array_key_exists('revoke',$_POST)){
revokeCurrent();
header("location:index.php?status=sold"); 
}
?>
<?php if( $_GET['status'] == 'sold'): ?>
<div class="card-sold-msg">
You Sold This Card for <?php echo $sale_price; ?> Fan Points
</div>

<?php endif; ?>

标题("位置:index.php?状态=已售出"(是唯一需要添加的。一旦RevokeCard((函数被执行,并且卡按预期售出/获得积分,页面将完全刷新。

最新更新