使用JSON更新Wordpress中的自定义帖子类型


Using JSON to update a custom post type in Wordpress

我有一个自定义的post类型,让我们称之为products。当用户将此产品拖到购物车(可丢弃的jQuery UI)时,我希望自定义帖子类型中名为"amount"的键减少一。

到目前为止,我已经通过jQuery$.ajax获得了一个JSON函数,它看起来像这样:

$.ajax({ url: 'http://localhost:8888/MAMP/nogg/wordpress/wp-content/themes/twentyeleven/functions.php',
    data: { postid: +id },
    type: 'post',
    success: function(output) {
        alert("amount is reduced by 1.");
    }
});

这将帖子的id发送到functions.php,然后我用它来获取我的functions.php 中的数据

if(isset($_POST['postid']) && !empty($_POST['postid'])) {
    $postid = $_POST['postid'];
    $response = json_decode($postid);
    remove_amount($response);
}

它调用带有postid的函数。

function remove_amount($postid) {
    $amount = get_post_meta($postid, 'amount', true);
    update_post_meta($postid, 'amount', $amount--);
}

这给了我一个500的错误,我已经确保发送的ID是正确的,并检查了包含密钥(金额)的字段的名称。

那么,我愚蠢的自己在这里缺少了什么?

您不需要json_decode $_POST['postid']变量。

$.ajax方法序列化数据对象,并像常规POST一样发送请求标头中的数据。jQuery没有向您的服务器发送JSON。(您可以更改ajax参数以实际发送JSON,但我不会因为安装wordpress而使您的生活复杂化。使用$.ajax的方式很好。)

这样试试:

if(isset($_POST['postid']) && !empty($_POST['postid'])) {
    // Make sure you do something in this function to prevent SQL injection.
    remove_amount($_POST['postid']);
}

另外,您的数据对象中的+id是什么?这是故意的吗?除此之外,您还需要向我们提供导致HTTP500的PHP错误。

如果将$single参数设置为true,则

get_post_meta返回一个字符串。

那么,您的错误是否与试图递减字符串值有关?

在递减之前,将您的量val强制转换为int怎么样?

function remove_amount($postid) {
    (int)$amount = get_post_meta($postid, 'amount', true);
    update_post_meta($postid, 'amount', $amount--);
}

您收到的错误消息的行(706)是否与您处理更新元的行相对应?

好的,我解决了。显然,WP函数文件中有一些内容不赞成处理这样的json内容。因此,我没有识别标准的WP函数(如get_post_meta),我所做的是创建一个空白页面,让它使用带有php代码的自定义模板,然后在jquery代码中链接到该WP页面。

$.ajax({ url: 'http://localhost:8888/MAMP/nogg/wordpress/?page_id=43',
               data: {postid2: id },
               type: 'post',
               success: function(output) {
      }
});

page_id=43是使用以下模板的页面:

<?php
/**
* Template Name: ajax template
* Description: ajax *
* @package WordPress
*/

if(isset($_POST['postid']) && !empty($_POST['postid'])) {
remove_amount($_POST['postid']);
}
function remove_amount($postid) {
$amount = get_post_meta($postid, 'amount', true);
if($amount > 0):
    update_post_meta($postid, 'amount', $amount-1);
    echo $amount-1;
endif;
}

现在代码正常运行,现在我只需要按照Stephen所说的做,并添加一些sql注入保护。谢谢你的回答!把我带向正确的方向!