fbpx

2 Feb /Global Custom Fields in WordPress with ACF Pro

Posted by Miguel Lozano

At T R I M, we frequently use the Advanced Custom Fields Pro plugin on our WordPress projects to give our clients flexibility to edit copy on custom page templates. Generally these custom fields are assigned and scoped to a specific Post or Page in your WordPress site. This week I was looking for a way to create custom fields that could be accessed from any Page or Post in the project.

After digging through documentation I found that ACF Pro gives us the ability to create fields which can be accessed globally, via an Options Page. ACF also provides a few functions to do the heavy lifting for us acf_add_options_page() and acf_add_options_sub_page().

Let’s take a look at how to use them.

functions.php


// First we check to see if acf_add_options_page is a function.
// If it is not, then we probably do not have ACF Pro installed
if( function_exists('acf_add_options_page') ) {
	
  // Let's add our Options Page
  acf_add_options_page(array(
    'page_title' 	=> 'Theme Options',
    'menu_title'	=> 'Theme Options',
    'menu_slug' 	=> 'theme-options',
    'capability'	=> 'edit_posts'
  ));
  
  // If we want to add multiple sections to our Options Page
  // we can do so with an Options Sub Page.
  acf_add_options_sub_page(array(
    'page_title' 	=> "Let's Work Together",
    'parent_slug'	=> 'theme-options',  // 'menu_slug' on the parent options page
    'menu_title'	=> "Let's Work Together",
    'menu_slug' 	=> 'lets-work-together',
  ));
  
  acf_add_options_sub_page(array(
    'page_title' 	=> 'Footer Settings',
    'parent_slug'	=> 'theme-options',
    'menu_title'	=> 'Footer Settings',
    'menu_slug' 	=> 'footer-settings',
  ));
  
}

 

With this setup, if we go back to our WordPress Dashoboard we can see that we now have our ‘Theme Options’ menu item, with our Options Sub Pages nested inside.

 

Now we can create our custom fields an add them to an Options [Sub] Page.

Under Location make sure that you set the Options Page equal to your desired Options Sub Page, where you would like to see this custom field.

We now have our custom fields available on the Options Sub Page.

 

To wrap this all up we just need to make a call to our custom fields in the page template.

// To add a your custom fields we'll use the usual suspects, the_field() or get_field().

// if we want to echo the field's content directly to our template
the_field('field_name, 'option');

// if we want to store the field's content in a variable to use later
$var_name = get_field('field_name', 'option');

To learn more about using Options with ACF Pro pages you can refer to the documentation.