Skip to content

Instantly share code, notes, and snippets.

@westcoastdigital
Created February 20, 2024 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westcoastdigital/c6e4ab00a7f9e0261707fc102df57bc7 to your computer and use it in GitHub Desktop.
Save westcoastdigital/c6e4ab00a7f9e0261707fc102df57bc7 to your computer and use it in GitHub Desktop.
Add Custom Conditional Logic to ACF
<?php
// Add WooCommerce Conditional Logic
function jm_acf_woo_product_filter($choices)
{
if (!isset($choices['WooCommerce'])) {
$new_choices = array();
foreach ($choices as $key => $value) {
$new_choices[$key] = $value;
if ($key == 'Post') { // position in the drop down in thios case after Post
$new_choices['WooCommerce'] = array(); // section heading
}
} // end foreach choices
$choices = $new_choices;
} // end if not in choices
if (!isset($choices['WooCommerce']['post'])) {
// the array value name 'woocommerce_product' is what will be referenced in subsequent functions
$choices['WooCommerce']['woocommerce_product'] = 'Product'; // the value in the drop down
}
return $choices;
}
add_filter('acf/location/rule_types', 'jm_acf_woo_product_filter');
// add choices
function jm_acf_woo_product_choices($choices)
{
// Conditional options
$array = [
'simple' => 'Simple',
'variable' => 'Variable',
'grouped' => 'Grouped',
'external' => 'External',
];
if (isarr($array)) {
foreach ($array as $value => $label) {
$choices[$value] = $label;
}
}
return $choices;
}
add_filter('acf/location/rule_values/woocommerce_product', 'jm_acf_woo_product_choices');
// Check conditional logic
function jm_acf_woo_conditional_render($match, $rule, $options)
{
$post_id = $options['post_id'];
if (!$post_id) {
return false;
}
// get product type which is what we want to check against the value in the options array
$product = wc_get_product($post_id);
if ($rule['operator'] == "==") {
// check for a match to set value as true
$match = ( $product->get_type() == $rule['value']);
} elseif ($rule['operator'] == "!=") {
// if not match set value as false
$match = ( $product->get_type() != $rule['value']);
}
// return true or false based on the conditional checks
return $match;
}
add_filter('acf/location/rule_match/woocommerce_product', 'jm_acf_woo_conditional_render', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment