Advanced Custom Fields in Page template

I’ve recently been doing quite alot of work with Advanced Custom Fields in WordPress, and find them incredibly useful when working with Posts, but cannot seem to get the same results when working with Pages.

I currently have a page that uses a loop to pull through all posts with the category ‘news’. The loop creates a structure for each news article and lists them 4 to a page, paginated, on the left hand side of the page. On the right hand side of the page I have a section that needs to show an attached ACF Post Object (in this case a single custom post type of ‘Staff’, assigned in the Pages edit section).

Read More

So on the left there is the loop for posts, and the right I need a Post Object to show. The only issue is that all the usual techniques for getting the post object data don’t seem to be working:

    <?php
        $post_object = get_field('attached_story');

        print_r($post_object);
    ?>

This returns nothing. I’ve put it inside the loop / outside the loop to no avail (which I imagine is why it’s not working, because it needs to be within a loop). The loop to display the posts is shown here:

    <?php
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = array('post_type' => 'news', 'showposts' => '4', 'paged' => $paged); 
        $the_query = new WP_Query( $args );
        ...
        if( have_posts() ) : while($the_query->have_posts()) : $the_query->the_post()
    ?>

My question is this – is there a particular approach to using post objects within page templates? Is there a different loop that needs to be instantiated in order to loop through the pages custom fields as opposed to a posts? And lastly is there a way to view the current pages array in its entirety, with all custom fields?

Related posts

Leave a Reply

2 comments

  1. Just in case anyone else runs into this problem in the future, the solution was to use the query_posts() method to set the loop instead of the ‘new WP_Query’ class call. My loop call now looks like this:

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    query_posts(array('post_type' => 'news','showposts' => '4', 'paged' => $paged));
    

    This is pulling through the attached story now using the following code:

    <?php
    $post_object = get_field('attached_story');
    if( $post_object ):         
    $post = $post_object;
    setup_postdata( $post ); ?>
    
        <?php $short_desc = get_field('short_description'); ?>
        All over operations...
    
    <?php wp_reset_postdata();?>
    <?php endif; ?>
    
  2. you can use the following code inside your loop:

    <?php $values = get_post_custom_values("your custom field name");
     if($values){?>
    <?php echo $values[0]; ?>
    <?php } ?>