Support

Account

Home Forums General Issues Post Object

Solved

Post Object

  • Hi, I don’t have something quite right. I want to return the title and the post_content of the object (from the field Location) but at the moment I’m getting the link and title for the post I’m on rather than from the object field and the test custom field is blank.
    The only output is ‘Post Object Custom Field:’ so its acknowledging that there is a post object.

        
    $post_object = get_field('location');
    
    if( $post_object ): 
    
    	// override $post
    	$post = $post_object;
    	setup_postdata( $post ); 
            
    	?>
        <div>
            	<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
        	<span>Post Object Custom Field: <?php the_field('test'); ?></span>
        </div>
        <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
    <?php endif;
  • It could have something to do with where you’re code is. Is it in a template file?

    The best suggestion I can give without understanding where you’re using this is to add

    
    global $post;
    

    like this

    
    $post_object = get_field('location');
    
    if( $post_object ): 
    
    	// override $post
            global $post;
    	$post = $post_object;
    	setup_postdata( $post ); 
            
    	?>
        <div>
            	<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
        	<span>Post Object Custom Field: <?php the_field('test'); ?></span>
        </div>
        <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
    <?php endif;
    
  • The code is in the single template file for the cpt.

    Your suggestion got the custom field working (the_field(‘test’) but the permalink and the title aren’t returning anything – specifically I need the title and the post content.

    Many thanks for your help

  • the_permalink() and the_title() have to be inside a while (have_posts())... loop.

    If you do not have a loop in the template then try using get_the_title($post_id) and get_the_permalink($post_id) which can be used outside of “The Loo”.

  • Of course. Got that working.

    How can I output the post content (main text area) rather than just the permalink?

  • 
    echo apply_filters('the_content', $post->content);
    

    I think

  • Whilst that didn’t work simply echo the_content(); did – must of been overthinking it.

    Many thanks for your help

  • OK so I wasn’t getting formatted content so I came up with this – works as expected so I assume its fine ?

    $content = apply_filters('the_content', get_post($post->ID)->post_content);

  • That looks good to me, if it works. I’ve read that it’s not straight forward to get the content of a post outside of the loop.

Viewing 10 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic.