Support

Account

Home Forums General Issues Post Object Field doesn't work within a Function Reply To: Post Object Field doesn't work within a Function

  • Hi guys.


    @Jonathan
    – nice code, but I think you need to reference global $post within the function like so:

    
    function example($field, $postID) {
    
         global $post;
    
         $post_object = get_field($field, $postID);
         
         if($post_object) {
              // get post data
    	  $post = $post_object;
        	  setup_postdata($post);
              ?>
                   <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
              <?php
              // reset postdata
    	  wp_reset_postdata();
         }
    }
    
    example(&#039;my_post_object&#039;, $post->ID); //in your template, assuming you do this inside the loop. If outside try replacing $post->ID with get_the_ID()
    ?>