As we know that get_post_meta() function is used to fetch meta values of a post like custom fields. Sometimes we face a problem with that function while we are fetching any data of any post through get_post_meta() in functions.php in any function.

I have wasted my 1:30 hours to resolve this and now I get a solution, I am sharing it to all to save your valuable time.

Solution : Just put

 global $post;

in the beginning of the function like below example.

For example we are fetching location of a event in any function in functions.php file like :

function my_eventrequest() {
                           global $post; // do not forgot to put this here

                           $sunil_args = array(  'post_type'  => 'event');
                           $custom_query = new WP_Query( $sunil_args);
                             if ( $custom_query->have_posts() ) {
	                                while ( $custom_query->have_posts() ) {
		                                 $custom_query->the_post();
                                                     $ev_location    = get_post_meta($post->ID, "event_location", true); // $ev_location variable having event location
                                                }
                                          }
                          }

 

If you are also facing same issues while trying to fetch any meta value, just modify your code with

 global $post;

and your issue will get resolve.
Share your tricks if you have any in comments 🙂