• Resolved janew

    (@janew)


    I have created a template based on single.php in TwentyEleven, using the following code to show the latest post from category 5:

    <?php // Display blog posts on any page
    		$temp = $wp_query; $wp_query= null;
    		$wp_query = new WP_Query(); $wp_query->query('showposts=1&cat=5');
    		while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
    					<?php get_template_part( 'content', 'single' ); ?>

    Works great!

    I tried to transplant that code into a new template based on singular.php in TwentyTwenty and it does not work – I get an error of ‘unexpected end of page’. I have checked repeatedly for missing } ; and ?> but everything is in its place.

    When adding the code, I removed

    	<?php
    
    	if ( have_posts() ) {
    
    		while ( have_posts() ) {
    			the_post();
    
    			get_template_part( 'template-parts/content', get_post_type() );
    		}
    	}
    
    	?>

    But if I re-add the ‘if’ statement and the corresponding braces, I get an error of ‘unexpected }’ so I am really lost!

    Can someone please explain what I am doing wrong, what I am missing, or if there is a better way to achieve what I want?

    *Note that yes I did change the old code to reflect the proper path to content.php in TwentyTwenty. And yes, I am using a child theme.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Your first piece of code doesn’t show the endwhile; although it should be there. So when you copied that code, you left out an important piece, and PHP couldn’t find it.
    In PHP, there are two ways to make a statement block. One is curly braces and the other is the colon and the corresponding end keyword. (There is endif and endwhile and endfor.)

    An alternative to making a page with page template for showing the latest post is to use the code found at stackexchange to allow a variable in the URL to cause a redirect to the latest post.

    Thread Starter janew

    (@janew)

    That’s it!
    After this code in the original, there is a bunch of mixed html/php that I didn’t need, followed by the usual get_footer();, so I completely missed the endwhile; that was buried in between. And since it wasn’t in the code I was replacing, I didn’t even think about it.

    Thank you for explaining that the colon replaces the opening brace – I wasn’t aware of that, and now it makes more sense as I never really understood why endwhile; would only show up sometimes.

    Thank you so much!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Show one post from certain category’ is closed to new replies.