Home › Forums › Backend Issues (wp-admin) › Dynamically set the value of a field
How can I set the value of an ACF, dependent upon the woocommerce product type?
I have this currently:
function whatis_single_product_type( $field ) {
$field['value'] = __('initialize', 'txtdomain');
global $post;
if( function_exists('get_product') ){
$product = get_product( $post->ID );
if( $product->is_type( 'variable' ) ){
$field['value'] = __('variable', 'txtdomain');
} elseif( $product->is_type( 'simple' ) ){
$field['value'] = __('simple', 'txtdomain');
}
}
return $field;
}
add_filter( 'acf/load_field/name=product_type_set', whatis_single_product_type );
Although this seems to work – saving the text, either ‘variable’ or ‘simple’ to the acf product_type_set (otherwise it stays set to ‘initialize’) – does anyone have a better way?
https://stackoverflow.com/questions/52254794/get-and-use-the-product-type-in-woocommerce
$field['value'] = $product->get_type();
So I’ve changed it to:
/* sets the acf to product type text */
add_filter('acf/load_field/name=product_type', function($field) {
global $post;
$field['value'] = get_product( $post->ID )->get_type();
return $field;
});
… which works, but I get an error (There has been a critical error on this website) when attempting to edit the field group for the acf. What can I do to avoid that (other than temporarily removing the filter above)?
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.