I'm making a custom meta field for posts.
In the back-end, get_post_meta works fine and returns the value.
In the front-end, it returns NULL:
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field); // NULL
echo $my_custom_field // ''
Things I tried and looked into:
my_custom_field gets written to the database with corresponding post_id, and everything seems fine.
Using hard-coded post ID gives the same result
Putting the call inside the loop gives the same result
QUESTION: Why get_post_meta returns NULL, how to fetch the actual value?
EDIT: The field is right there in the database:
meta_id post_id meta_key meta_value
139 87 my_custom_field IT works!
The function arguments reference correct post_id and meta_key which I have checked multiple times, including hard-coding the arguments.
I have also tried to change the name of the meta_key as suggested in some other answer - didn't work.
Backend code is basically this tutorial https://www.smashingmagazine.com/2011/10/create-custom-post-meta-boxes-wordpress/
EDIT 2:
No errors in my logs.
Here is the complete front-end code which returns NULL instead of expected value:
add_action( 'the_post', 'output_my_custom_field');
function output_my_custom_field() {
$post_id = get_the_ID();
if ( !empty( $post_id ) ) {
$my_custom_field = get_post_meta( $post_id, 'my_custom_field', true );
var_dump($my_custom_field);
}
}
EDIT 3: Regardless of the hook used (I tried various ones), or even calling a function without any hooks - it still returns NULL.