The variable $count
is accessible in the scope of the current function only. So whatever happens inside get_template_part()
cannot know that variable.
You could use a global variable, which is accessible everywhere as $GLOBALS['count']
. But then you risk collisions with plugins and maybe other code.
I recommend a helper function for the functions.php
:
/**
* 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;
}
You can use that function to remember any number you want. In your example that should look like this:
<?php
// Reset the counter
wpse_count( FALSE );
if ( have_posts() ) : // Start the Loop
while ( have_posts() ) :
the_post();
wpse_count( 1 );
get_template_part( 'content', get_post_format() );
endwhile;
endif;
?>
And in the template part file you print the value without adding anything:
echo wpse_count();
Example in TwentyEleven’s content-status.php
<?php
the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyeleven' ) );
echo 'Number: ' . wpse_count();
?>