我有可变产品,其中包含属性和术语 . 我为每个产品属性术语“external_name”创建了(使用ACF)一个额外的自定义字段 .
我正在使用此代码在ACF中获取自定义规则(请参阅最后的屏幕截图):
add_filter( 'acf/location/rule_types', function( $choices ){
$choices[ __("Other",'acf') ]['wc_prod_attr'] = 'WC Product Attribute';
return $choices;} );
add_filter( 'acf/location/rule_values/wc_prod_attr', function( $choices ){
foreach ( wc_get_attribute_taxonomies() as $attr ) {
$pa_name = wc_attribute_taxonomy_name( $attr->attribute_name );
$choices[ $pa_name ] = $attr->attribute_label;
}
return $choices;} );
add_filter( 'acf/location/rule_match/wc_prod_attr', function( $match, $rule, $options ){
if ( '==' === $rule['operator'] ) {
$match = $rule['value'] === $options['ef_taxonomy'];
} elseif ( '!=' === $rule['operator'] ) {
$match = $rule['value'] !== $options['ef_taxonomy'];
}
return $match;}, 10, 3 );
我需要在Attribute的下拉列表中更改Term的名称,具体取决于其Custom字段(如果不为空) .
这是我的代码来自 functions.php
:
function filter_woocommerce_variation_option_name( $term_name ) {
$attribute_taxonomies = wc_get_attribute_taxonomies();
if ( $attribute_taxonomies )
{
foreach ($attribute_taxonomies as $tax)
{
if (taxonomy_exists(wc_attribute_taxonomy_name($tax->attribute_name))){
$taxonomy = wc_attribute_taxonomy_name($tax->attribute_name);
$terms = get_terms($taxonomy,
array(
'orderby' => 'name',
'order' => 'ASC',
"hide_empty" => false
)
);
/** Loop through every term */
$external = '';
foreach($terms as $term){
$termId = $term->term_id;
if ($external = get_field('external_name', $term->taxonomy . '_' . $term->term_id)) {
?><pre><?php print_r($term_name) ?></pre><?php
$term_name = $external;
}
}
}
}
}
return $term_name;
};
add_filter( 'woocommerce_variation_option_name', 'filter_woocommerce_variation_option_name', 10, 1 );
现在,我从自定义字段中获取了1个更改的名称,用于所有条款 . 有什么想法吗?
Additional details:
我正在使用ACF(不是PRO) .
Woocommerce - 版本3.3.5 .
Wordpress - 版本4.9.5
我在里面创建了一个自定义字段 "External Attribute Name" 的CF组 "Attribute Fields" (参见下面的屏幕截图) .
1 回答
Updated (解决空属性值错误和代码优化)
以下是使用单变量产品页面的产品属性下拉列表中的ACF自定义字段值替换产品属性Term Name的正确代码:
代码位于活动子主题(或活动主题)的function.php文件中 . 经过测试和工作 .