我正在尝试向我的woocommerce订单添加自定义字段“ Color”,但是此自定义字段必须位于几个特定类别中,例如类别“ ballons”,因此functions.php中的代码是这样的:
add_action('woocommerce_before_add_to_cart_button','wdm_add_custom_fields');
/**
* Adds custom field for Product
* @return [type] [description]
*/
function wdm_add_custom_fields()
{
global $product;
ob_start();
$terms = get_the_terms( $product->get_id(), 'product_cat' );
// Loop through term objects
foreach( $terms as $term ) {
if ( "ballons" === $term->slug ) {
?>
<div class="wdm-custom-fields">
<label>Color </label>
<select type="text" name="wdm_name">
<option value="blue">Blue</option>
<option value="red">Rojo</option>
<option value="green">Green</option>
</select>
</div>
<div class="clear"></div>
<br>
<?php
// break; // The term match, we stop the loop.
}
}
?>
选择框出现在所有产品中,似乎上面的代码并不将选择框限制为特定类别,请提供任何帮助
改为使用专用的Wordpress条件函数has_term()
,如下所示:
add_action('woocommerce_before_add_to_cart_button', 'before_add_to_cart_button_custom_fields');
function before_add_to_cart_button_custom_fields() {
global $post, $product;
// Here define your terms (can be terms Ids, slugs or names)
$terms = array('ballons');
if ( has_term( $terms, 'product_cat' ) ) {
?>
<div class="wdm-custom-fields">
<label><?php _e("Color", "woocommerce"); ?></label>
<select type="text" name="wdm_name">
<option value="blue"><?php _e("Blue", "woocommerce"); ?></option>
<option value="red"><?php _e("Rojo", "woocommerce"); ?></option>
<option value="green"><?php _e("Green", "woocommerce"); ?></option>
</select>
</div>
<div class="clear"></div>
<br>
<?php
}
}
代码进入您的活动子主题(或活动主题)的functions.php文件中。经过测试和工作。
您应该在代码中
wdm_name
的color
任何地方简单地替换
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句