WooCommerce支持可變商品默認支持 SKU、價格、庫存數(shù)量、商品圖片、體積、重量等常用選項,一般情況下,這些選項足夠我們做一個常規(guī)的商城了,可是有時候,這些字段是不夠用的,比如,一個面向全國的商城,產(chǎn)品在不同的倉庫里面存放,我們需要在可變商品字段里面添加一個“存放倉庫”的字段,以便我們更好的處理商品和訂單,其他開源商城系統(tǒng)我沒研究過,不知道能不能實現(xiàn),WooCommerce二次開發(fā)實現(xiàn)這個是非常簡單的。

添加自定義字段到WooCommerce可變商品
把以下代碼放到當前使用的WooCommerce主題的 functions.php 中即可。
function variable_fields( $loop, $variation_data ) {
?>
<tr>
<td>
<div>
<label><?php _e( '存放地點', 'woocommerce' ); ?></label>
<input type="text" size="5" name="my_custom_field[<?php echo $loop; ?>]" value="<?php echo $variation_data['_my_custom_field'][0]; ?>"/>
</div>
</td>
</tr>
<?php
}
function variable_fields_js() {
?>
<tr>\
<td>\
<div>\
<label><?php _e( '存放地點', 'woocommerce' ); ?></label>\
<input type="text" size="5" name="my_custom_field[' + loop + ']" />\
</div>\
</td>\
</tr>\
<?php
}
function variable_fields_process( $post_id ) {
if (isset( $_POST['variable_sku'] ) ) :
$variable_sku = $_POST['variable_sku'];
$variable_post_id = $_POST['variable_post_id'];
$variable_custom_field = $_POST['my_custom_field'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $variable_custom_field[$i] ) ) {
update_post_meta( $variation_id, '_my_custom_field', stripslashes( $variable_custom_field[$i] ) );
}
endfor;
endif;
}
調(diào)用WooCommerce可變商品自定義字段
添加的自定義字段其實就是 WordPress 的自定義字段,調(diào)用的時候直接使用get_post_meta調(diào)用即可。
global $product;
$available_variations = $product->get_available_variations();
foreach ($available_variations as $prod_variation) :
$post_id = $prod_variation['variation_id'];
$post_object = get_post($post_id);
$my_custom_field = get_post_meta( $post_object->ID, '_my_custom_field', true);
end foreach;
WooCommerce作為一個 WordPress 電子商務插件,為我們提供了非常豐富靈活的接口,非常方便我們二次開發(fā)定制。如果需要定制WooCommerce主題或插件,可以直接咨詢 WordPress 智庫。



寫不錯哦,需要的東西在你這兒找到了