如何使用AJAX更新wordpress上的post meta

Dav*_*tos 0 php ajax wordpress

我有以下代码:

<form method='post'>
<input type='submit' name='bid' value='Licitar'>
Run Code Online (Sandbox Code Playgroud)

当用户单击提交按钮时,我想更新WordPress帖子元,以便更改实际的出价值.

我还想在不重新加载页面的情况下更新以下div:

<div class='vehicle-value-box'>".auctionplugin_get_latest_bid($post->ID).",00€</div>
Run Code Online (Sandbox Code Playgroud)

我怎么能两个都做?我很难理解如何捕获$ _POST值并使用它来做上面提到的事情.我需要在哪里放置PHP处理代码并将其包含在WordPress ajax核心中?

编辑:

现在我的代码看起来像在page.php(INSIDE THE 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'>
Run Code Online (Sandbox Code Playgroud)

和我的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);
}
Run Code Online (Sandbox Code Playgroud)

Ria*_* C. 5

编辑:因为您在评论中指定了没有值输入,我进行了相应的编辑.

首先,您要确保在前端定义了wordpress的ajaxurl,因为您可以使用此代码.(在examples.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;
}
Run Code Online (Sandbox Code Playgroud)

其次,您应该创建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>
Run Code Online (Sandbox Code Playgroud)

最后我们需要处理wordpress中的数据,因为我们应该在主题functions.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);
}
Run Code Online (Sandbox Code Playgroud)