Home > database >  If statement in Wordpress PHP
If statement in Wordpress PHP

Time:12-20

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"
        
?>

CodePudding user response:

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")

CodePudding user response:

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()
  • Related