I have used $count before, but never run into this problem. I cannot get it to work. I have limited php background, so please be patient with me! Here is the $count setup code:
<?php $count = 0; ?>
<?php if ( have_posts() ) : // Start the Loop ?>
<?php $count++; ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php endif; ?>
Within content.php - here is what I am trying to do:
<?php if ($count == 1) { ?>
<section class="stories-title">
<img src="<?php bloginfo('stylesheet_directory'); ?>/assets/stories-title.jpg" />
</section>
<?php ;} ?>
Can anyone explain to me what's happening? To the best of my knowledge, I'm running into an undefined variable issue, but I'm not sure how to fix this without breaking the $count... do the conditional statements and content have to be in the same file for $count to work?
UPDATE: The issue (as described below) was with variable scope - the $count variable does not carry over when using template_part. Here is the fixed code:
functions.php
// remember number (so we can count posts)
/**
* Remember a number.
*
* @param int|FALSE $add A number to add, or FALSE to reset the counter to 0 (zero).
* @return int
*/
function wpse_count( $add = 0 )
{
static $counter = 0;
if ( FALSE === $add )
$counter = 0;
else
$counter += (int) $add;
return $counter;
}
index.php
<?php wpse_count( FALSE ); ?>
<?php if ( have_posts() ) : // Start the Loop ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php wpse_count( 1 ); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php endif; ?>
content.php
<?php if (count_posts() == 1) { ?>
<section class="stories-title">
<img src="<?php bloginfo('stylesheet_directory'); ?>/assets/stories-title.jpg" />
</section>
<?php ;} ?>
Additional Solution
For a MUCH simpler solution to this problem, see a different answer below. Just needed to use wp_query
<?php if ( $wp_query->current_post == 0 ) { ?>
No $counter needed.
get_template_part()
. That function is really just a fancy wrapper for the PHPinclude()
function. The problem, which again is not specific to WordPress, is that variable scope does not pass through the PHPinclude()
call.