Multiple IDs in PHP call in WordPress - php

** 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 '';
}
?>

Related

Best way to simplify statement

I have the following php code.
Im trying to find out the field name/key that does not exist without using hardcoded static text. Is there a php function that can do this. array_keys_exist is similar to what I want but it only allows for checking of a single key.
ex:
Something like
$keys_to_confirm = ['password','password_old',....];
$user_submitted_input_array = ['password'=>'...', 'somekey'=>'...' ];
bool : all_array_keys_exist($keys_to_confirm,$user_submitted_input_array);
Current code that uses static text to report the missing field/key name
if( isset($input['password']))
{
if( isset($input['password_old'])) )
{
if(isset($input['password_repeat'])) )
{
//good to go!
}
else
{
die('missing form element password_repeat.');
}
}
else
{
die('missing form element password_old.');
}
}
else
{
die('missing form element password.');
}
I had this code but it doesnt say what is missing.
//if the field doesnt exist for some reason lets create a dummy
if( ! isset($input['password'])
OR (!isset($input['password_repeat']))
OR (!isset($input['password_old'])) )
{
die('missing form element.');
}
Try:
foreach( array('password', 'password_repeat', 'password_old') as $key ) {
if( empty($input[ $key ]) ) {
echo 'Missing field: ' . $key;
}
}
You can probably come up with a one liner to do this using array_diff_key, but I think the above is concise enough.
Here's the one liner with array_key_diff. It's not the prettiest but functional.
$keys_to_confirm = array('password' => '','password_old' => '');
$user_submitted_input_array = array('password'=>'...', 'somekey'=>'...');
$validate = array_diff_key($keys_to_confirm, $user_submitted_input_array);
if( empty($validate) ) {
echo 'Passed';
} else {
echo 'Missing field: ' . key($validate);
}
My solution:
if ($field_miss = array_diff_key(array('password', 'password_old', '...'), array_keys($input))) {
echo 'Missing field: ', implode(', ', $field_miss);
}

PHP include pages error

Still trying to get how PHP works :)
Kindly help me with one solution & idea, here is when i'm using:
<?php
$content = array(
'id01'=>'sub_id01.php',
'id02'=>'sub_id02.php'
);
if(in_array($_GET['show'], array_keys($content))) {
include($content[$_GET['show']]);
} else {
include('sub_id00.php');
}
?>
and:
<?php
$content = array(
'id00'=>'N/A',
'id01'=>'ID01',
'id02'=>'ID02',
);
if(!empty($_GET['show']) && isset($content[$_GET['show']])) {
echo $content[$_GET['show']];
} else {
echo $content['id00'];
}
?>
Where first example includes pages and second includes simple code inside ''
Problem is that if there is no ID set (index.php) ut shows default page/code. And if wrong ID set, it'll also show default page/code.
How to update it so without any ID set it would show default page and if some wrong ID set, it would show some error page/code?
Cheers!
UPDATE!
After a while reqding i've updated it with:
<?php
$content = array(
'id01'=>'sub_id01.php',
'id02'=>'sub_id02.php'
);
if (in_array($_GET['show'], array_keys($content)))
{
include($content[$_GET['show']]);
}
elseif (isset($_GET['show']))
{
include('sub_error.php');
}
else {
include('sub_id00.php');
}
?>
And:
<?php
$content = array(
'error'=>'error msg',
'id00'=>'N/A',
'id01'=>'ID01',
'id02'=>'ID02',
);
if(!empty($_GET['show']) && isset($content[$_GET['show']]))
{
echo $content[$_GET['show']];
}
elseif (isset($_GET['show']))
{
echo $content['error'];
}
else
{
echo $content['id00'];
}
?>
:)
$content = array(
'id01'=>'sub_id01.php',
'id02'=>'sub_id02.php'
);
if (isset($_GET['show']))
{
if (array_key_exists($_GET['show'], $content))
{
//$_GET id is set and it exists in content
include($content[$_GET['show']]);
}
else
{
//$_GET id is set but does not exist in content
//include whatever page you have for a wrong id here
}
}
else
{
//else no $_GET was set
//include default page
}

How can I place text that relates to a foreach function, outside the loop?

I'm really unsure how to describe this, so please forgive me.
Basically, I'm reading from an XML, and then generating an IF statement that checks all records in the XML and if a condition matches, details about that record is displayed.
What I want to add, is a similar function but in reverse, but outside the foreach loop, so it's only displayed once.
foreach($xml as $Reader) { $items[] = $Reader; }
$items= array_filter($items, function($Reader) use ($exclude) {
if($Reader->Picture == 'None' || in_array($Reader->Pin, $exclude)) {
return false;
}
return true;
});
usort ($items, function($a, $b) {
return strcmp($a->Status,$b->Status);
});
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
}
}
if (!$items) { echo "Please check back in a moment when our readers will be available!"; }
So, in the XML file each Reader has a Status that can be one of three values: Available, Busy or Logged Off.
So what I'm doing, is for each record in the XML, checking if the Reader status is available.. and if so, echo the above line.
But I want to add in, that if NONE of the readers show as 'Available' to echo a single line that says 'Please check back in a moment'.
With the code above, ifthere are four readers online, but they're all busy.. nothing is displayed.
Any ideas?
Just use a simple boolean value
$noneAvailable = true;
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$noneAvailable = false;
}
}
if ($noneAvailable) {
echo "Please check back in a moment";
}
I managed to take the answer given above, and combine it with XPath to just filter the records in the XML based on the status given using xPath.
include TEMPLATEPATH."/extras/get-readers.php";
$readers = $xml->xpath('/ReaderDetails/Reader[Status="Available"]');
$gotOps = false;
foreach ($readers as $Reader)
{
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$gotOps = true;
}
if ($gotOps!=true)
{
echo 'Please check back in a moment when our readers will be available!';
}

How do I clean up this if/else statement? (refactoring)

I know there must be a nicer way to do this, but whenever I search "&&" i don't get good enough results...
<?php
if (empty($row[ContactName]) && empty($row[ContactEmail]) && empty($row[ContactPhone]) && empty($row[Website])){
echo "Not Provided";
}
else{
...do stuff...
}
?>
Thanks!
What is wrong with the original code?
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
Looks like fine code to me...
<?php
$i=1;
$ar=array('ContactName','ContactEmail','ContactPhone','Website')
foreach($ar as $a)
if (empty($row[$a]))
{
$i=0;
break; //to make code fast
}
if($i) //do stuff
else echo 'not provided';
?>
or if you really want to make your code extra small then change your column name in database
From To
ContactName Col1
ContactEmail Col2
ContactPhone Col3
Website Col4
and then do
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
else echo 'Not Provided';
?>
However it is not good to rename column as it will make your db somewhat less understandable.
As php functions have a lot of inconsistency, It's always a good idea using a library to make it more consistent.
put this function in that library:
function empty()
{
foreach(func_get_args() as $arg) if (empty($arg)) return false;
return true;
}
usage:
if (empty($row[ContactName], $row[ContactEmail], $row[ContactPhone], $row[Website])) {
echo "Not Provided";
}
you could make it as short as this if compactness was more important than readability :)
$required = array('ContactName', 'ContactEmail', 'ContactPhone', 'Website');
$ra = array_filter(array_intersect_key($row,array_flip($required)));
if(empty($ra)){
echo "Not Provided";
}
else{
//....
}
you can't put array_filter inside empty() or you get "Fatal error: Can't use function return value in write context"
1) array flip is turning your $required values into keys
2) array_intersect_key throws away any $row keys not found in $required
3) array_filter throws away any empty values
leaving you with a zero length array, which is empty. No need to worry about array lengths or loops
<?php
$flag = 1;
if (empty($row[ContactName])){
$flag = 0;
}
if (empty($row[ContactEmail])){
$flag = 0;
}
if (empty($row[ContactPhone])){
$flag = 0;
}
if (empty($row[Website])){
$flag = 0;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
?>
OR
$flag = 1;
$i=0;
$mustarray = array('ContactName','ContactName','ContactName','ContactName'); //or any number of fields that you want as mandatory
foreach($yourresult as $row){
if(empty($row[$mustarray [$i]])){
$flag = 0;
}
$i++;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
Do not play with making arrays and stuff just to make code look nicer.
As Tommy pointed
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
this code is nice, just need proper formatting like he pointed.
Making arrays and then launching loop will decrease performance
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
?>
this might look small, nice and "pro", but has more operations to give same results as a simple if instruction.
Not saying that it cant be done faster, i don't know php well, just remember about code executing speed.

Optimising a PHP If/Else statement

I'm attempting to optimise the following PHP If/Else statement. Could I rewrite the code to make use to case and switch, or should I leave it as it is, or what?
Code:
if(empty($_GET['id'])){
include('pages/home.php');
}elseif ($_GET['id'] === '13') {
include('pages/servicestatus.php');
}elseif(!empty($_GET['id'])){
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if(!$rawdata){
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
}else{
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if(!$rawdata){
error_404();
}
}
Thanks
I hate switch statements, but its personal preference to be honest. As far as further optimization i'd suggest taking a look at some form of assembly language. It will give you some general ideas on how to make conditional statements more efficient. That is, it will give you a different out look on things.
if(!empty($_GET['id']))
{
if($_GET['id'] == '13')
{
include('pages/servicestatus.php');
}
else
{
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if (!$rawdata) {
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
} else {
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if (!$rawdata) {
error_404();
}
}
}
else
{
include('pages/home.php');
}
switch would be appropriate if you had several discrete values for $_GET['id'] that you were checking for.
One suggestion I can make for the sake of readability is that
} elseif (!empty($_GET['id'])) {
only needs to be
} else {
Well i don't think it's necessary to switch to a swith
but you could change
} elseif (!empty($_GET['id'])) {
to just
}else{
You may want to look into breaking up your code into a MVC form; that would make it much easier to maintain your code. At least put the last clause into another file, probably called default.php and include it. Also, you might create an array of id => file key/value sets, lookup the id, and include the file.
if (isset($_GET['id'])) {
$pages = array(
0 => 'home.php',
13 => 'servicestatus.php'
);
if (isset($pages[$_GET['id']])) {
include('pages/' . $pages[$_GET['id']]);
} else {
include('pages/default.php');
}
}
Yes, switch is evaluate once, is efficient than if elseif,
and is easier to maintain with this given structure
switch ($_GET['id'])
{
case 13: ... break;
case 0 : ... break;
default: ... break;
}
I dont know, if you should, or should not, but here I wouldnt. The main reason is, that there is at least one statement, you can omit, and then, you will have just a if-elseif-else-Statement
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
elseif (!empty($_GET['id'])) { /* code* }
is the same as
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
else { /* code* }
In the block after that, the statement if(!$rawdata) is also duplicated.

Categories