Designer just starting out with PHP looking for a more elegant solution
I’m trying to a create a div that only appears beside posts if they have comments. The only
code I can get to work is below & that’s by creating two variables I feel a more experienced person than myself wouldn’t need, I just can’t express what I’m looking for with code. This is my first week working with php so I’ve been googling for solutions & can only find examples of generating the number of comments with the wordpress function get_comments_number(); & then hiding the divs that have 0 with javascript which seems overly complicated for something so trivial.
I like to have something more like the bottom piece of code especially the way it outputs the singular & plural comments text after but I’m not competent enough yet.
Any examples / advice would be greatly appreciated
<?php
$b = 0;
$commBox = get_comments_number();
if($commBox <=$b) {
echo "";
}else{
echo "<div class="commentbox"> $commBox </div>";
}?>
<?php if ( have_comments() ); ?>
<div class="commentbox">
<?php printf( _n( '1 comment;', '%1$s comments;', get_comments_number(), 'ves'),
number_format_i18n( get_comments_number() ) ); ?>
</div>
Have you tried running the following code. This would only create a div if the post did have comments, meaning you wouldn’t need any JavaScript to hide ones without, as they wouldn’t exist:
Notice the use of the
comments_number()
function which is good for what you wanted to do in regards to showing different values based on single or multiple comments. The function reference can be found here.A clean up to the top code (which I think is what you’re asking for would be:
This just basically checks that $commBox is true (in PHP 0 is false, non zero numbers are true) and removes the uneccessary
echo ""
.You could create a have_comments() function just by having a function that returns get_comments_number() but I’m not sure that’s necessary.
Edit: Something like:
Should show “comments” if there are more than 1 comment and “comment” if there is one comment (though this is untested).