skip to Main Content

Newbie to PHP. My interior if statement isn’t working properly. It just echos "2022."

<?php

$c = 0;
if ( have_posts() ) :
    while ( have_posts() ) :
        the_post(); 
        
        if (the_time('Y')=="2021") :
            echo "Loop";
            $c++;
        endif;
        
    endwhile;
     
    
endif;
echo "Count = $c"
        
?>

2

Answers


  1. the_time outputs/echos the current time; it does not return it.

    Displays the time at which the post was written.

    You want get_the_time instead:

    Retrieves the time at which the post was written.

    if (get_the_time('Y') === "2021")
    
    Login or Signup to reply.
  2. I would strongly encourage you to adopt the "conventional" syntax for PHP control structures:

    <?php
    
    $c = 0;
    if ( have_posts() ) {
        while ( have_posts() ) {
            the_post();            
            if (the_time('Y')=="2021") {
                echo "Loop";
                $c++;
            }  
        }
    }
    echo "Count = $c"
            
    ?>
    

    The vast majority of PHP code you’ll find uses C syntax (with curly braces), vs. the "Alternative syntax" in your example. Since you can’t readily mix’n’match the two styles … and since you’re "still learning" … using the curly braces will help eliminate any potential "confusion" or "potential bugs"..

    ALSO:

    • including both "if (has_posts())" and "while (has_posts())" might be redundant. Look here for a detailed explanation.
    • To answer your question, use get_the_time()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search