2012-01-24 25 views
0

我有一個自定義帖子類型,可以稱之爲產品。當用戶將此產品拖放到購物車(可拖放的jQuery UI)時,我希望我的自定義帖子類型中名爲「金額」的鍵減少1。使用JSON更新Wordpress中的自定義帖子類型

到目前爲止,我有通過jQuery $就一個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。

那麼我在這裏失去了什麼?

回答

0

您不需要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是什麼?那是故意的嗎?除此之外,你需要給我們造成了HTTP 500

+0

是的,這是一個很好的觀點。在我來到這裏之前,我把它作爲最後一次努力扔在那裏。它不會以任何方式工作。謝謝你的回答,清楚什麼時候以及爲什麼要使用json_decode! :) – ninja

+0

啊是的!我可以檢查php_error.log的細節,完全分開。錯誤日誌說:PHP致命錯誤:在/Applications/MAMP/bin/mamp/nogg/wordpress/wp-content/themes/twentyeleven/functions.php調用未定義功能get_post_meta()上線706完全博格爾斯我的腦海裏。是否有可能阻止它處理json的functions.php中的某些內容?我應該嘗試用該函數加載一個新的.php文件嗎? – ninja

0

get_post_meta的回報,如果你設置了$單參數去真實的,你有一個字符串的PHP錯誤。

那麼,您的錯誤是與嘗試減少字符串值有關嗎?

在遞減之前將你的val值轉換爲int值怎麼辦?

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

您收到的錯誤消息的行(706)是否與您正在處理更新元的行對應?

0

好的,我解決了它。顯然在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; 
} 

現在的代碼運行,因爲它應該,現在我只是需要做什麼斯蒂芬說,並添加一些SQL注入防護。感謝您的答案!讓我走向正確的方向!

相關問題