foreach statement echo once if nested foreach is empty? - php

OK I have a foreach statement searching for a keyword across 3 multisite blogs in wordpress like so:
<?php
foreach ( $blogs as $blog ):
switch_to_blog($blog['blog_id']);
$search = new WP_Query($query_string);
if ($search->found_posts>0) {
foreach ( $search->posts as $post ) {
echo "POST CONTEN";
}
}elseif ($search->found_posts===0) {
# code...
$notfound = true;
}
endforeach;
if ($notfound) {
# code...
echo "POST NOT FOUND";
}
This works fine if there are no posts using the keyword across all thre blogs it echos the POST NOT FOUND but if there is a post on blog 1 but not on blog 2 or 3 it still echos POST NOT FOUND why?
Chris
//********UPDATE***********************************/
<?php
$searchfor = get_search_query(); // Get the search query for display in a headline
$query_string=esc_attr($query_string); // Escaping search queries to eliminate potential MySQL-injections
$blogs = get_blog_list( 0,'all' );
$notfound = true;
foreach ( $blogs as $blog ):
switch_to_blog($blog['blog_id']);
$search = new WP_Query($query_string);
if ($search->found_posts>0) {
$notfound = false;
}
if($notfound){
?>
<div class="post">
<h2><?php _e('Ingen resultater'); ?></h2>
<p><?php _e('Beklager, vi fant ingen innlegg som samsvarer med ditt søk: ' . get_search_query()); ?></p>
</div>
<?php
}else{
foreach ( $search->posts as $post ) {
echo "content";
}
}
endforeach;
?>

Your logic is backwards. You should start with a "nothing found" condition, and change it to false when something is found:
$not_found = true;
while ...
if ($search->found_posts != 0) {
$not_found = false;
}
}
if ($not_found) {
echo 'nothing found'; // $not_found is true
} else {
echo 'found something'; // $not_found is false
}

Sorry about the formatting. Just copied your code here. Do the opposite of what your doing, look at the variable $found here.
<?php
$found = false;
foreach ( $blogs as $blog ):
switch_to_blog($blog['blog_id']);
$search = new WP_Query($query_string);
if ($search->found_posts>0) {
foreach ( $search->posts as $post ) {
echo "POST CONTEN";
}
$found = true;
}elseif ($search->found_posts===0) {
# code...
}
endforeach;
if ($found == false) {
# code...
echo "POST NOT FOUND";
}

Related

If meta key's value is x then echo

I have 3 pieces of code that essentially should do the same thing, but none of them are working and they are all echoing "Not Working!".
The meta key is wilcity_belongs_to and the value is 2980. These are all based on what plan a listing is on. So if the listing plan is value 2980 then it must echo "Working!".
$meta = get_post_meta( get_the_ID(), 'wilcity_belongs_to',true );
if( $meta == '2980' ) {
echo "Working!";
} else {
echo "Not Working!";
};
and
global $wpdb;
$wpdb->get_results( "select * from $wpdb->wpam_postmeta where meta_key = 'wilcity_belongs_to' " );
if ( $wilcity_belongs_to == '2980') {
echo "Working!";
} else {
echo "Not Working!";
};
and
if ( get_post_meta( $post->ID, 'wilcity_belongs_to', true ) == '2980' ) {
echo "Working!";
} else {
echo "Not Working!";
};
Here is a screenshot of what is in the database: Database
This is in Table: wpam_postmeta
Please could i get help on this, ive been trying everything.
Did you try this way? get_results() usually returns an array with the result set.
global $wpdb;
$result = $wpdb->get_results( "select * from $wpdb->wpam_postmeta where meta_key = 'wilcity_belongs_to' " );
foreach ($result as $row) {
if ( $row["wilcity_belongs_to"] == '2980') {
echo "Working!";
} else {
echo "Not Working!";
};
};

PHP- How to solve else in nested foreach loop

This my code syntax all conditions are working but last else is not working. I found solution in there https://stackoverflow.com/a/5930255/7688968 and I am used break 2 but still not working. How can I solve that?
<?php
$rows = $wpdb->get_results( "SELECT * FROM test WHERE approve_status = '1'" );
if($rowcount>0)
{
foreach ($rows as $row)
{
if ( is_user_logged_in() )
{
echo 'I am user';
$demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
foreach($demo as $demos)
{
if(!empty($demos->id)){
echo 'I am IF';
break 2;
}
else{
echo 'I am last ELSE';
}
}
}
else{
echo 'I am guest user';
}
}
}
You are doing the else in the wrong place, it should be done instead of the foreach...
$demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
if(!empty($demo)){
foreach($demo as $demos)
{
echo 'I am IF';
}
}
else{
echo 'I am last ELSE';
}
So the logic is that if no records are returned then display your message.
Because the break doesn't break if's. You need to break the foreachs only once, so it's just break;
That else actually doesn't run, because the if is not false. If it uses break in the ifs, else won't run at all. The innermost else runs only, if the very first id of $demos is empty. The second only when if the user is not logged in. These don't relate too much for the foreach cycles.
Move whole foreach block in the function and return from it when needed. For example:
if($rowcount>0)
{
doStuff($rows);
}
function doStuff($rows) {
global $wpdb, $curentmail;
foreach ($rows as $row)
{
if ( is_user_logged_in() )
{
echo 'I am user';
$demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
foreach($demo as $demos)
{
if(!empty($demos->id)){
echo 'I am IF';
return;
}
else{
echo 'I am last ELSE';
}
}
}
else{
echo 'I am guest user';
}
}
}

Warning: Illegal string offset 'enabled' in

We are trying to break up a form into several pages using jQuery steps. The error points to the form that we're trying to create. Call to the form initially looks like this:
$enable_paid_submission = houzez_option('enable_paid_submission');
$user_pack_id = get_the_author_meta( 'package_id' , $userID );
$remaining_listings = 0;
if( is_page_template( 'submit_property_test.php' ) ) {
if( $enable_paid_submission == 'membership' && $remaining_listings != -1 && $remaining_listings < 1 ) {
print '<div class="user_package_status"><h4>'.esc_html__('HTMLhere.','houzez' ).'</h4></div>';
<?php
$layout = houzez_option('property_form_sections');
$layout = $layout['enabled'];
if ($layout): foreach ($layout as $key=>$value) {
switch($key) {
case 'features':
get_template_part( 'features' );
break;
case 'location':
get_template_part( 'location' );
break;
case 'multi-units':
get_template_part('multi-units');
break;
}
}
endif;
?>
We would like to break the three sections of the form (features, location and multi-units) into three different pages. We added jQuery steps and it now looks like the following:
<script>
$(function ()
{
$("#wizard").steps({
headerTag: "h2",
bodyTag: "section",
transitionEffect: "fade"
});
});
</script>
<div id="wizard">
<h2>Features</h2>
<section>
<?php
$layout = houzez_option('property_form_sections');
$layout = $layout['enabled'];
if ($layout): foreach ($layout as $key=>$value) {
switch($key) {
case 'description-price':
get_template_part('features');
break;
}
}
endif;
?>
<h2>Location</h2>
<section>
<?php
$layout = houzez_option('property_form_sections');
$layout = $layout['enabled'];
if ($layout): foreach ($layout as $key=>$value) {
switch($key) {
case 'description-price':
get_template_part('location');
break;
}
}
endif;
?>
</section>
<h2>Multi-units</h2>
<section>
<?php
$layout = houzez_option('property_form_sections');
$layout = $layout['enabled'];
if ($layout): foreach ($layout as $key=>$value) {
switch($key) {
case 'description-price':
get_template_part('multi-units');
break;
}
}
endif;
?>
</section>
It was running okay in the first few hours. Now it is returning the error.
It looks like you are expecting the the function call to houzez_option() to return an array. It would seem from the error that you are getting that it is not. Without seeing what the houzez_option() code looks like it is impossible to tell you why it is not.
You could still improve your code some by having it check specifically for what you expect to be returned from your function.
$layout = isset( $layout['enabled'] ) ? $layout['enabled'] : '';
if ( is_array( $layout ) ): foreach ($layout as $key=>$value) {
switch($key) {
case 'description-price':
get_template_part('features');
break;
}
}
else:
echo 'Unable to retrieve options';
endif;
This will prevent the error and alert you that it isn't working on the frontend. You could also make the message clearer for the enduser. I was just providing a generic example.

If parent slug equals

I'm trying to write an if statement where, if a child page's has a slug equal to a specific value, a different statement is echoed. Regardless of the slug value, the function always returns the else value rather than any other.
<?php
global $post;
$post_data = get_post($post->post_parent->post_name);
if ($post_data == 'slug-one'){
$ticket = 'Cats';
} elseif ($post_data == 'slug-two') {
$ticket = 'Dogs';
} else {
$ticket = 'Birds';
}
echo $ticket;
?>
Any ideas as to how I can better write the statement, or what the error occurring is?
As it turns out, I shouldn't have called $post_data = get_post($post->post_parent->post_name). My fixed code is below. Thanks for the advice everyone.
<?php
global $post;
$post_data = get_post($post->post_parent);
if ($post_data->post_name == 'in-the-city'){
$ticket = 'Cats';
} elseif ($post_data->post_name == 'on-the-beach') {
$ticket = 'Dogs';
} else {
$ticket = 'Birds';
}
echo $ticket;
?>

Multiple IDs in PHP call in WordPress

** I apologize for being unclear - I meant I want "Summit Sponsors" to display once regardless of how many IDs are used. Just for it to be hidden if no IDs are used. Thanks **
I was wondering if anyone knew a clean way to use multiple custom fields in an IF statement.
At the moment I have it spaced out, so each custom field "SponsorHeading#" has it's own if/else statement:
<?php
if(get_post_meta($post_id, 'SponsorHeading1', true)) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
if(get_post_meta($post_id, 'SponsorHeading2', true)) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
?>
and so on for 3 more custom fields. I'd like to have something cleaner like:
<?php
if(get_post_meta($post_id, 'SponsorHeading1', true)) || if(get_post_meta($post_id, 'SponsorHeading2', true)) || if(get_post_meta($post_id, 'SponsorHeading3', true)) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
?>
or something along those lines to clean it up but nothing I've tried has worked.
Any suggestions?
Not 100% sure on if there is a more efficient way to manage this within WordPress’s logic itself, but the simplest solution I can conceive of using the example you give is to put all of the ids into an array & have logic to loop through them like so:
<?php
$fields = array('SponsorHeading1', 'SponsorHeading2', 'SponsorHeading3');
foreach($fields as $field_value) {
if(get_post_meta($post_id, $field_value, true)) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
}
?>
EDIT: Addressing the user edits to the question. So how about this? We loop through the fields, and the value of $has_value changes to TRUE if at least one of the fields is returned by get_post_meta(). And if $has_value is TRUE then act on it:
<?php
$fields = array('SponsorHeading1', 'SponsorHeading2', 'SponsorHeading3');
$has_value = FALSE;
foreach($fields as $field_value) {
if(get_post_meta($post_id, $field_value, true)) {
$has_value = TRUE;
}
}
if ($has_value) {
echo '<h2>Summit Sponsors </h2>';
}
else {
echo '';
}
?>

Categories