I have my WordPress posts looped and listed out by year successfully. However, I am unsure why I still received a warning message.

Warning: Undefined variable $year_check

Below are the codes that I used on my custom theme. Can anyone please give me some guidance?

<?php if( have_posts() ) : ?>
    <div id="section-2023" class="blog_news-section">
        <div class="blog_news-items">
            <?php while( have_posts() ) : the_post(); ?>
                <?php $year = get_the_date( 'Y' );
                if($year !==$year_check){
                echo "<h3>" . $year . "</h3>";
                $year_check = $year;
                <article class="blog_news-item">
                    <a href="<?php the_permalink(); ?>" class="blog_news-link">
                        <div class="blog_news-img"><?php the_post_thumbnail(); ?></div>
                        <p class="blog_news-date"><?php echo get_the_date(); ?></p>
                        <p class="blog_news-name"><?php the_title(); ?></p>
            <?php endwhile; ?>
        <?php kyoob_2023_paging_nav(); ?>
<?php endif; ?>

Thank you in advance for your kind help, and I look forward to and appreciate all the support here.

1 Answer 1


The issue is here:

if($year !== $year_check){

The first time that conditional is used in the loop - $year_check has not been defined.

The solution is to simply define it before this: <?php if( have_posts() ) : ?>

For example:

<?php $year_check = 0; ?>
<?php if( have_posts() ) : ?>
  • Oh~ you have saved my day. Thanks, @shanebp
    – Danc Chan
    Nov 25, 2023 at 0:27
  • Since the answer helped you - please accept it by clicking on the checkmark next to the answer.
    – shanebp
    Nov 25, 2023 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.