我在一个站点上实现了一个Wishlist功能,主要基于本教程Tuts和Create AJAX Wishlist插件。除了Rest API调用的stock输出之外,它的工作方式与预期一样--它返回“instock”或“outofstock”,而我正拼命想办法让它返回一个格式化的字符串(例如,“in stock!”用span包装)。我昨天花了大部分时间试图以我知道的任何方式格式化它,但没有成功。
下面是插件PHP文件中代码的相关部分:
register_rest_field('product',
'stock',
array(
'get_callback' => 'rest_stock',
'update_callback' => null,
'schema' => null
)
);
而且
function rest_stock($object,$field_name,$request){
global $product;
$id = $product->get_id();
if ($id == $object['id']) {
return $product->get_stock_status();
}
}
结果通过以下简化的js输出:
.done(function(response){
$('.wishlist-items').each(function(){
var $this = $(this);
$.each(response,function(index,object){
$this.append('<li class="wishlist-item" data-product="'+object.id+'"><span class="wishlist-item-stock">'+object.stock+'</span></li>');
});
});
})
谁能给我指出正确的方向吗?!谢谢!
感谢@cbroe的指导,我成功地:
function rest_stock($object,$field_name,$request){
global $product;
$id = $product->get_id();
$status = $product->get_stock_status();
if ($id == $object['id']) {
if ( 'instock' == $status ) {
$stockformatted = '<span class="wishlist-is">In stock!</span>';
}
if ( 'outofstock' == $status ) {
$stockformatted = '<span class="wishlist-oos">Out of stock</span>';
}
return $stockformatted;
}
}