我有以下代码:
<form method='post'>
<input type='submit' name='bid' value='Licitar'>
当用户点击提交按钮时,我想更新WordPress帖子元,以便更改实际出价值。
我还想在不重新加载页面的情况下更新以下div:
<div class='vehicle-value-box'>".auctionplugin_get_latest_bid($post->ID).",00€</div>
我怎么能两个都做?我很难理解如何捕获$ _POST值并使用它来执行上述操作。我需要在哪里放置PHP处理代码并将其包含在WordPress ajax核心中?
编辑:
现在我的代码看起来像在page.php上(在LOOP中,它与PHP一起“回应”):
<div id='vehicle-value-box".$post->ID."'>".get_post_meta(get_the_ID(),'start_price', true).",00€</div>
(...)
<div class='vehicle-auction-box'>
<script>
jQuery('input[type=submit]').click(function(e) {
e.preventDefault();
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: 'action=newbid&id=".$post->ID."',
success: function(msg){
jQuery('#vehicle-value-box".$post->ID."').html(msg+',00€');
}
});
</script>
<div>
<form method='post'>
<input type='submit' name='bid".$post->ID."' value='Licitar' class='bidvalue'>
我的functions.php:
add_action('wp_ajax_newbid', 'newbid_ajax');
function newbid_ajax() {
$post_id = $_POST['id'];
$mybid = get_post_meta($post_id, 'start_price', true);
$mybid = $mybid + 100;
update_post_meta($post_id,'start_price',$mybid);
die($mybid);
}
答案 0 :(得分:5)
编辑:由于您在评论中指定了没有值输入,因此我进行了相应的编辑。
首先,您要确保在前端定义了wordpress的ajaxurl,因为您可以使用此代码。 (在例如的functions.php中插入)
add_action('wp_head','my_ajaxurl');
function my_ajaxurl() {
$html = '<script type="text/javascript">';
$html .= 'var ajaxurl = "' . admin_url( 'admin-ajax.php' ) . '"';
$html .= '</script>';
echo $html;
}
其次,您应该创建一个ajax调用,为此在包含该表单的页面中添加此脚本标记:
<script>
jQuery('input[type=submit]').click(function(e) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: "action=newbid&id="+<?php echo $post->ID?>,
success: function(msg){
jQuery('.vehicle-value-box').html(msg+",00€");
}
});
})
</script>
最后我们需要处理wordpress中的数据,因为我们应该在主题函数中使用这个动作.php:
add_action('wp_ajax_newbid', 'newbid_ajax');
function newbid_ajax() {
$post_id = $_POST['id'];
//Get current bid
$mybid = get_post_meta($post_id, 'start_price', true);
//Increase the bid, for example the amount here is 100€
$mybid = $mybid + 100;
//Update the database with the increased bid value
update_post_meta($post_id,'start_price',$mybid);
// In case you need to update another meta for the user, you
// can access the user ID with the get_current_user_id() function
// Finally sending back the updated bid so the javascript can display it
die($mybid);
}