Skip to content

Instantly share code, notes, and snippets.

@mtruitt
Created April 20, 2024 15:10
Show Gist options
  • Select an option

  • Save mtruitt/3635b9194d69ec2de52b54a05aedbf33 to your computer and use it in GitHub Desktop.

Select an option

Save mtruitt/3635b9194d69ec2de52b54a05aedbf33 to your computer and use it in GitHub Desktop.
A custom function designed to safely retrieve field values from the Advanced Custom Fields (ACF) plugin, ensuring seamless operation and preventing fatal errors in case of plugin deactivation. Additionally, it includes built-in functionality to display a site notice, alerting administrators if the ACF plugin is disabled.
<?php
/**
* Retrieves a custom field value using Advanced Custom Fields (ACF) plugin.
*
* @param string $field_name The name of the ACF field.
* @param array $options Optional. An array of options to pass to the `get_field()` function. Default is an empty array.
* @return mixed The value of the ACF field, or an empty string if ACF plugin is disabled.
*/
function custom_get_acf_field($field_name, $options = '') {
if ( function_exists('get_field') ) {
// ACF function exists, so it's safe to use
return get_field($field_name, $options);
} else {
// ACF plugin is not active, display a notice
add_action('admin_notices', 'custom_acf_plugin_disabled_notice');
return ''; // or any default value you prefer
}
}
/**
* Displays an error notice when the ACF plugin is disabled.
*/
function custom_acf_plugin_disabled_notice() {
?>
<div class="notice notice-error">
<p><?php esc_html_e('The Advanced Custom Fields plugin is currently disabled. Please enable it to use this feature.', 'TEXT_DOMAIN'); ?></p>
</div>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment