最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to add custom attribute to all outofstock and all instock products automatically?

programmeradmin0浏览0评论

What I want to achieve is to add the custom attribute "instock" to all in-stock products and "outofstock" for products that out of stock right now. Why? Because I want to add those attributes to filter plugin, that doesn't support sorting by stock status

I think construction will be something like this, but I don't know how to add attributes ( Also, i`m pretty sure, that this hook woocommerce_get_availability is not the best solution to get actual statuses all the time

add_filter( 'woocommerce_get_availability', 'woocommerce_stock_availability_attributes', 1, 2);
function woocommerce_stock_availability_attributes( $availability, $_product ) {
   if ( ! $_product->is_in_stock() ) {
       //some magic stuff
   }
  return $availability;
}

What I want to achieve is to add the custom attribute "instock" to all in-stock products and "outofstock" for products that out of stock right now. Why? Because I want to add those attributes to filter plugin, that doesn't support sorting by stock status

I think construction will be something like this, but I don't know how to add attributes ( Also, i`m pretty sure, that this hook woocommerce_get_availability is not the best solution to get actual statuses all the time

add_filter( 'woocommerce_get_availability', 'woocommerce_stock_availability_attributes', 1, 2);
function woocommerce_stock_availability_attributes( $availability, $_product ) {
   if ( ! $_product->is_in_stock() ) {
       //some magic stuff
   }
  return $availability;
}
Share Improve this question edited Oct 19, 2019 at 10:58 kh1 asked Oct 19, 2019 at 10:47 kh1kh1 12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

WooCommerce already saves a custom metadata called _stock_status. This metadata can have these values:

instock
outofstock
onbackorder

You don't need to create your own metadata as that would be redundant and more difficult to keep in sync with WooCommerce data.

发布评论

评论列表(0)

  1. 暂无评论