Getting a conditional message out of a foreach loop - php

I'm displaying all the posts in the category that have a valid date as follows -
<?php $blog = $pages->find('posts');
foreach($blog->children() as $blogpost): ?>
<?php if ($blogpost->title() <= $latest && $blogpost->category == $thisCat): ?>
//HTML for displaying post goes here
<?php endif ?>
<?php end foreach ?>
That works fine when those posts validate my condition, and displays nothing if it doesn't. What I want to do is display an error message (like 'there are no posts here') when there are no posts that pass the condition. I can't just do a simple else condition in that if query because it's inside the foreach loop. I can't take the if query out of the foreach loop because it relies on a variable that is defined as part of it ($blogpost).
Kind of stuck in this catch 22... Any suggestions?

How about...
<?php
$blog = $pages->find('posts');
$found_something = false;
foreach($blog->children() as $blogpost) {
if ($blogpost->title() <= $latest && $blogpost->category == $thisCat) {
$found_something = true;
//HTML for displaying post goes here
}
}
if(!$found_something) {
// display error message
}
?>
By the way, is there a specific reason why you're using the alternative PHP syntax?

I'd create a counter variable which increments each time when you display a post.
<?php $blog = $pages->find('posts');
$displayedPosts = 0;
foreach($blog->children() as $blogpost): ?>
<?php if ($blogpost->title() <= $latest && $blogpost->category == $thisCat):
$displayedPosts++; ?>
//HTML for displaying post goes here
<?php endif ?>
<?php end foreach ?>
<?php
if ($displayedPosts == 0) {
echo 'ERROR!';
}
?>
Using a boolean variable (as tmh did) is probably better in this case unless you want to count the posts.

Just count your posts , if it's 0 display just the message , else execute foreach loop :
<?php $blog = $pages->find('posts');
if(count($blog->children())==0){ echo 'No post Here'; }
else{
foreach($blog->children() as $blogpost): ?>
<?php if ($blogpost->title() <= $latest && $blogpost->category == $thisCat): ?>
//HTML for displaying post goes here
<?php endif ?>
<?php end foreach ?>
<?php } ?>

Related

If I leave an else empty , it falses my posts that are counting on "posts_per_page" on Wordpress, how to correct that?

I have a condition that says :
if the posts are superiors of today -> show
else -> //do nothing, I leave empty and then my posts disappear if there are inferiors of today.
But the problem is that I have 10 posts per page but because of this empty else I have only 7 who appear for example.
So how can I say in the empty else to display the following posts which are still valid ?
Here's my code :
<?php if (get_field('fin_de_levenement')){ ?>
<?php $now = time();
$date_one_timestamp = strtotime(get_field('fin_de_levenement', false, false));
if ($now < $date_one_timestamp ) { ?>
<div>my content</div>
<?php } else {
// do nothing
} ?>
Thank you !
Just remove your else statement.
<?php if (get_field('fin_de_levenement')){ ?>
<?php $now = time();
$date_one_timestamp = strtotime(get_field('fin_de_levenement', false, false));
if ($now < $date_one_timestamp ) { ?>
<div>my content</div>
<?php }

Changing $_Post Search Results To Words Rather Than Category Number

On my custom search results page I have a line that displays what category and price. The code I'm using is
Displaying results for <?php echo $_POST['category_name']; ?>
The output for this code is "Displaying results for 18120".
I'm looking to display the word "Audio" rather than "18120", as well as about 10 other categories.
My current attempt, shown below, is not working properly.
<?php $cat = $_POST['category_name']; ?>
<?php if ($cat == 18120) echo 'Audio';
elseif ($cat == 18121) echo 'Television';
?>
In the else/if, store the new name, rather than echoing it. Then use that variable in your display:
<?php $cat = $_POST['category_name']; ?>
<?php if ($cat == 18120) $cat = 'Audio';
elseif ($cat == 18121) $cat = 'Television';
?>
Displaying results for <?php echo $cat; ?>
To save aload of else and if why not use the good old switch and case?
switch ($_POST['Category_name']){
case 18120:
$Cat = "Audio";
break;
case 18121:
$Cat = "Television";
break;
case 18122:
$Cat = "Something Else";
break;
}
echo $Cat;
Use get_category() wordpress function:
<?php
$catCode = $_POST['category_name'];
if(is_numeric($catCode)) {
$cat = get_category($catCode);
echo $cat->name;
} else {
echo $catCode;
}
?>
Enjoy your code!

WordPress post views from the_views as a variable

I am using the WordPress plugin WP-PostViews to display the number of views a post has. I am using this code and it works great:
<?php if(function_exists('the_views')) { the_views(); }?>
The thing I want to do is to use this number of post views as a variable but I can't get it working. So far I have tried:
<?php if(function_exists('the_views')) { $variable = the_views(); } ?>
and
<?php if(function_exists('the_views')) { $variable = the_views(); } else { $var = 0; } ?>
No success so far. Does anyone have suggestions?
By default the_views() echos instead of returns. You can get a return by setting the first argument to false. Example:
<?php if(function_exists('the_views')) { $variable = the_views(false); } ?>

Switching from "if" to "elseif" breaks code

I'm using multiple if statements to check a containing div, and output an image based on the container name. The code was working fine until I add a final "else" or change the if's out to elseif and I can't figure out why that's happening. When I try to add the else or elseif, the entire page fails to load. Any idea why this is happening?
<?php
if($viewMore['container_type'] == 'Large IMG' || $viewMore['container_type'] == 'Gallery') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'large_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$large = 0; foreach ($photoArray as $photo => $upload): if (++$large == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach ?>
<?php } ?>
<?php
elseif($viewMore['container_type'] == 'Medium IMG') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'small_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$medium = 0; foreach ($photoArray as $photo => $upload): if (++$medium == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach; ?>
<?php } ?>
<?php else { ?> SOMETHING HERE <?php } ?>
EDIT:
Other notes
I've tried wrapping the break; in brackets because I thought that piece following the count might be messing with something. Also removing the counter altogether or adding a semi colon after the endforeach didn't help.
Whenever you close your PHP block, think about all the text/HTML outside it being put into PHP's echo function.
What gave me alarm bells was this part:
<?php } ?>
<?php else { ?> ...
What that translates into is:
if (...) {
} echo "[whitespace]"; else {
}
which clearly makes your else block unexpected.
You should not close the PHP block between your closing if and opening else, i.e. do this instead:
...
} else {
...

PHP shorthand/shortcode conditional IF statement: execute code or return message

I have a foreach loop inside of an if statement. My code is in shorthand format. I do not want the foreach loop to execute if the if condition returns true and instead echo out a message 'sorry database is empty!'
Functional Code
<?php if (!$check == 0) : ?>
<?php foreach... ?>
...
<?php endforeach; ?>
<?php endif; ?>
<?php if ($check == 0) echo 'Sorry database is empty!'; ?>
What I don't like about this code is that I have two separate if conditions. Granted it works as it should but I would prefer to to have an else in the first if.
What is the proper syntax for what I want to do?
Alternatively if your answer is something like this:
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
Explain how that would stop the foreach from executing.
Just use an else:
<?php if ($check !== 0) : ?>
<?php foreach... ?>
...
<?php endforeach; ?>
<?php else: echo 'Sorry database is empty!'; ?>
<?php endif; ?>
You can also shorten this:
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
to just this:
$var_is_greater_than_two = ($var > 2); // returns true
Why not just add an else to the if ? The code block looks like special rendering, similar to Zenf Framework view script. Unless the special syntax disallows an else, you should be able to do this way.
<?php if (!$check == 0) : ?>
<?php foreach... ?>
...
<?php endforeach; ?>
<?php else : ?>
Sorry database is empty!
<?php endif; ?>
And idea could be to extract the foreach loop to another method.
Another file or same file have your executeLoop method:
<?php
function executeLoop()
{
foreach(..)
{
//do something
}
}
?>
enter code here
A few lines of code later, you can :
<?php (condition)?executeLoop() : echo $something;?>
The good thing is you can reuse your code if you wish later.

Categories