Retrieving ACF fields outside the loop
ACF’s get_field() function works inside the WordPress loop without extra arguments, but when you need to read a field value from functions.php, an AJAX handler, or a template for a different post, you have to pass the post ID explicitly.
Problem: How do you retrieve an ACF field value from any context, including functions.php?
Solution: Pass the post or page ID as the second argument: get_field( 'some_field', $page_id ). It works for any post type.
Where to get the ID
- Inside the loop: no ID is needed, or use
get_the_ID(). - Outside the loop, for the page being viewed:
get_queried_object_id(). It works even when the global$postis not set. - The static front page:
get_option( 'page_on_front' ); the blog page:get_option( 'page_for_posts' ). - Options page fields: use
'option'instead of an ID,get_field( 'field_name', 'option' ).
Example: reading ACF fields in an AJAX handler
An AJAX request runs in a separate PHP request to admin-ajax.php, so WordPress does not know which page the visitor is on. The page has to send its ID along with the request.
Step 1. Pass the page ID and a nonce to JavaScript. Register your script and add the data with wp_localize_script():
add_action( 'wp_enqueue_scripts', 'helloadmin_enqueue_page_script' );
function helloadmin_enqueue_page_script() {
wp_enqueue_script( 'page-script', get_template_directory_uri() . '/js/page.js', array( 'jquery' ), null, true );
wp_localize_script( 'page-script', 'pageData', array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'pageId' => get_queried_object_id(),
'nonce' => wp_create_nonce( 'page-data' ),
) );
}
Step 2. Send it as an AJAX parameter:
jQuery.post( pageData.ajaxUrl, {
action: 'get_example',
page_id: pageData.pageId,
nonce: pageData.nonce
}, function( response ) {
console.log( response );
} );
Step 3. In the AJAX handler in functions.php, check the nonce and use the ID to read the field:
add_action( 'wp_ajax_get_example', 'helloadmin_get_example' );
add_action( 'wp_ajax_nopriv_get_example', 'helloadmin_get_example' );
function helloadmin_get_example() {
check_ajax_referer( 'page-data', 'nonce' );
$page_id = absint( $_POST['page_id'] ?? 0 );
$example = get_field( 'example', $page_id );
wp_send_json_success( $example );
}
absint() makes sure only a number gets through. Keep in mind that a visitor can send any ID, so do not use this pattern to read fields from private or draft posts.