Support

Account

Home Forums General Issues echo custom field content from most recent post in a certain category

Solved

echo custom field content from most recent post in a certain category

  • I have a field called ‘hello-readers’, in posts in Category ID 3. Functionally the content in the hello-readers field should display on the home page, but only from the most recent published post.

    What I’m trying to do is get the most recent post, then echo the content from the hello-readers field.

    This code will be placed in the page template, and should only be called when the home page is displayed.

    I have had an attempt at cobbling together some PHP code. HTML is good, but PHP is very minimal, but there is something wrong with my syntax. The error I am receiving is:

    Parse error: syntax error, unexpected T_ENDWHILE, expecting ‘,’ or ‘;’ in /home/jameswilliams904/…/content-page.php on line 58

    Apologising for my lack of PHP coding skills, could someone please review my code and offer a suggestion of what I’ve got wrong? Many thanks in advance.

    <?php if(is_home()) { 
    $cat_id = 3; //the certain category ID
    $latest_cat_post = new WP_Query( array('posts_per_page' => 1, 'category__in' => array($cat_id)));
    if( $latest_cat_post->have_posts() ) : while( $latest_cat_post->have_posts() ) : $latest_cat_post->the_post();  
    echo get_field('hello-readers')
    endwhile;
    }
    endif; ?>

    Kind regards,
    JAMES WILLIAMS

  • Hi @jameswilliams90

    Your code is a bit of a jumble mate. I would definitely take some time to comment, indent and prettify you code.

    What you want to write is this:

    
    <?php 
    
    if( is_home() )
    { 
    	$cat_id = 3; //the certain category ID
    	
    	$posts = get_posts(array(
    		'posts_per_page' => 1,
    		'category__in' => array($cat_id)
    	));
    	
    	
    	// get recent
    	$recent = $posts[0];
    	
    	
    	// echo
    	echo get_field('hello-readers', $recent->ID)
    }
    
    ?>
    
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘echo custom field content from most recent post in a certain category’ is closed to new replies.