【发布时间】:2021-06-12 16:53:51
【问题描述】:
我在网站上实现了愿望清单功能,很大程度上基于本教程Tuts Plus Create AJAX Wishlist Plugin。它按预期工作,除了来自 Rest API 调用的库存输出 - 它返回“instock”或“outofstock”,我正在用头撞砖墙,试图弄清楚如何让它返回格式化的字符串(例如“有货!”包裹在一个跨度中)代替。我昨天大部分时间都在尝试以我知道的任何方式对其进行格式化,但没有成功。
以下是插件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>');
});
});
})
有人可以指出我正确的方向吗?!谢谢!
【问题讨论】:
-
那么不要直接返回
$product->get_stock_status(),而是检查它包含的内容——并在此基础上返回您的替代文本/html。 -
谢谢你!
标签: javascript php jquery wordpress woocommerce