Reputation: 5768
I am using the advanced custom field
plugin for Wordpress
. I am having difficulty displaying a field
on my page.
Basically I've created a field group and assigned id's
to the members of that group. I then use the get_field('field_name')
function to store the value of this field in a variable and echo
it on the screen. However this is returning false
.
I've also tried using the_field('field_name')
but this returns null
. I then read somewhere If you are trying to access a field outside of the Wordpress loop you must pass the post id
as a parameter to the get_field()/the_field()
methods.
I've tried that and still the same result...Does anyone have any idea as to what is the problem?
This is my code:
<?php get_header();
$postID = get_the_ID();
the_field('the-title', $postID); //Nothing being returned...
die();
?>
Upvotes: 8
Views: 36798
Reputation: 1
ACF has one more function
get_fields([$post_id], [$format_value]);
which returns a value of provided ID. but if we provide only id then by default it considers as post id
but if you provided an ID that is not an id of a post but user, term category, comment, and options tables ID then you have to prefix it like this:
// Get values from the current post.
$fields = get_fields();
// Get values from post ID = 1.
$post_fields = get_fields( 1 );
// Get values from user ID = 2.
$user_fields = get_fields( 'user_2' );
// Get values from category ID = 3.
$term_fields = get_fields( 'term_3' );
// taxonomy name.
$term_fields = get_fields( 'category_3' );
// Get values from comment ID = 4.
$comment_fields = get_fields( 'comment_4' );
// Get values from ACF Options page.
$option_fields = get_fields( 'options' );
// using 'option'.
$option_fields = get_fields( 'option' );
as described in the official docs
I found this when I have to work on a project where I need the value of category term id. this is worked for me outside of the loop.
Upvotes: 0
Reputation: 21
I had this issue. This was the format of function:
function get_field( $selector, $post_id = false, $format_value = true ) {
// ...
}
and I used it like this:
get_field( 'event_date', false, false) {
// ...
}
Upvotes: 1
Reputation: 536
If you're using WP_Query()
before using get_field()
, you need to reset the query using wp_reset_query()
function. I hope it'll solve this issue.
Upvotes: 16
Reputation: 561
You need to create a loop, then inside that loop you can retrieve the data.
<?php while( have_posts() ) : the_post() ?>
<?php $variable = the_field('the-title'); ?>
<?php endwhile; ?>
Upvotes: 3
Reputation: 19328
You're using get_the_ID() outside of the loop.
http://codex.wordpress.org/Function_Reference/get_the_ID
You could try:
global $post;
the_field( 'the-title', $post->ID );
But this would depend on what page you're on.
Which template file is this being used in?
Upvotes: 4