Safely call ACF functions without fatal errors when the plugin is deactivated.
Check for the ACF class before calling any ACF functions:
<?php
if ( class_exists( 'ACF' ) ) {
$value = get_field( 'hero_title' );
echo esc_html( $value );
}
Or check for a specific function:
<?php
if ( function_exists( 'get_field' ) ) {
$value = get_field( 'hero_title' );
echo esc_html( $value );
}
In a theme’s functions.php, wrap all ACF-dependent code:
<?php
add_action( 'acf/init', function () {
// This only runs when ACF is active.
acf_add_options_page( [
'page_title' => 'Theme Settings',
'menu_slug' => 'theme-settings',
] );
} );
For plugins that depend on ACF, add a dependency check on activation:
<?php
add_action( 'admin_notices', function () {
if ( class_exists( 'ACF' ) ) {
return;
}
echo '<div class="notice notice-error"><p>';
echo '<strong>My Plugin</strong> requires <a href="https://www.advancedcustomfields.com/" target="_blank">Advanced Custom Fields</a> to be installed and active.';
echo '</p></div>';
} );
Using class_exists( 'ACF' ) is preferred over function_exists( 'get_field' ) because it checks for ACF specifically, not just any plugin that might define a get_field() function.