Change icons depending a php condition - php

I assign a color value to each category of elements. I retrieve the color that has that category and I use it as background-color in a <span> in the following way:
<span class="cat-icon" style="background-color: <?php echo esc_attr( $first_ctg->get_color() ) ?>;">
What I need to do is that depending on the value of that color, I must show one image source or another inside the <span>.
if ($first_ctg->get_color() == red)
show img_01
elseif ($first_ctg->get_color() == blue)
show img_02
endif;
How can I do this properly in PHP?

There are more ways you could do this, I assume you have just two pictures (you can use elseifs otherwise). Solution:
<span class="cat-icon" style="background-color: <?php echo esc_attr( $first_ctg->get_color() ) ?>;">
<?php
$src = "img_02";
if ($first_ctg->get_color() == "red") {
$src = "img_01";
}
?>
<img src="<?php echo $src ?>">
I am finding out the image source in conditions first and then assigning its value to variable $img. Then I am echoing source to src inside php tags.

You can do this with PHP by checking the value of $first_ctg->get_color() and echoing the entire <span> element based on that value, i.e.
switch ( $first_ctg->get_color() ) {
case 'red': // or whatever value you would expect to receive from your get_color() function
echo '<span class="cat-icon" style="background-color:#ACOLOR"><img src="PATH/TO/WHATEVER/IMAGE"><span>';
break;
case 'another color':
echo '<span class="cat-icon" style="background-color:#ANOTHERCOLOR"><img src="PATH/TO/ANOTHER/IMAGE"><span>';
break;
...
default:
echo '<span class="cat-icon" style="background-color:#ANOTHERCOLOR"><img src="PATH/TO/ANOTHER/IMAGE"><span>';
break;
}
It's worth stating that this is arguably a case for using Javascript (or JQuery) to manipulate the DOM based on other elements or attributes, but since your question specifically asked how to do this in PHP that's the answer I gave.

Its Very Simple you need to put some conditions like
if ($first_ctg->get_color() == red)
{
$src = "https://www.example.com/img/background.png";
}
elseif ($first_ctg->get_color() == blue)
{
$src = "https://www.example.com/img/background-2.png";
}
And Into img tag you need to put this variable (i.e: $src)
<img src="<?php echo $src;?>" title="">

Since a category already knows its color. Why not make the icon also a property of the category class ? Then in your vieuw you could simply write something like
<img src="<?php echo $first_ctg->get_icon()">

Related

WordPress IF statement isn't outputting ELSE

I have a straightforward if statement to evaluate whether or not an image is set to appear as the logo on a WordPress build. If it returns empty/false, it displays a default image whose location is set as an absolute value.
The problem is when an image ISN'T set, the else statement is failing. I'm not receiving an error, but the code returned is simply an image tag without any source i.e. "< img src >".
Here is the statement:
<?php
$logo = $wp_options['header_logo'];
if(isset($logo) && ($logo !='')) { ?>
<img src="<?php echo $logo['url']; ?>">
<?php } else { ?>
<img src="wp-content/themes/wpdev/images/logo.png">
<?php } ;?>
I guess that if statement is failing, because you are treating $logo variable as a string.
It seems you're using $logo variable as an array, if you want to check out if it is empty you can use is_null() function of PHP.
By the way, we can't understand your problem this way, you should be more specific. Share your error or warning messages, the way it's behaving, etc..
Found a solution to this by specifically referring to the url of the image array when the variable $logo was defined. This way, the IF is evaluating the URL of the image.
The problem seemed to be that the initial IF was being evaluated as TRUE but obviously not returning the URL as this wasn't originally specified in $logo. By looking for the URL in the 'header_logo' array, it corrected the problem.
<?php
$logo = $wp_options['header_logo']['url'];
if(isset($logo) && ($logo !='')) { ?>
<img src="<?php echo $logo; ?>">
<?php } else { ?>
<img src="<!-- Image Location -->">
<?php } ;?>

How to implement PHP inside a image src code?

<img src="socimages/logo/"<?php if ($soca == ""){ echo "logo.jpg"; } else { echo $anotherimage . ".jpg";} ?>>
Basically what I am trying to do is to change the end part of the image src, to pick from a range of specifically named images.
The syntax for the code is obviously not right since I closed the src after /logo/ with the ". But if I do not have the " then my php will not function.
I would suggest, don't mess the logic in your img tag.
<?php
$img = ($soca == "") ? "logo.jpg" : $anotherimage.".jpg";
?>
<img src="socimages/logo/<?php echo $img; ?>" />
Use a ternary, and remember to distinct between "" and '' :
<img src="socimages/logo/<? echo $soca == '' ? 'logo.jpg' : $anotherimage . '.jpg'; ?>">
This will produce a correct <img src="image.jpg"> tag.
A ternary conditional makes the line shorter:
<img src="socimages/logo/<?php echo ($soca=='')?'logo.jpg':$anotherimage.'.jpg';?>">
This is probably shortest:
<img src="socimages/logo/<?php echo ($soca=='')?'logo':$anotherimage;?>.jpg">
Or even this variant, but it depends on the short tags configuration of your site:
<img src="socimages/logo/<?= ($soca=='')?'logo':$anotherimage;?>.jpg">
But all variants are horrible style. You should always try to implement in a transparent manner, easy to read and understand. So instead store the final path inside a variable and echo that into the src attribute of the img tag.

How to loop these pictures properly

I am sure this is a simple principle of PHP, however it is one I am yet to learn. In principle the code works:
<?php
for($i=0;$i<count($photos);$i++){
if($photos[$i]->image != ""){
if(JPATH_ROOT.'/images/'.$row->id.'/medium/'.$photos[$i]->image){
if(!$photocount) {
$photocount = $photocount + 1;
$photoclass = "property_photo_main property_photo_main_" . $photocount; // First Photo Class
}
?>
<img src="<?php echo JURI::root()?>images<?php echo $row->id;?>/medium/<?php echo $photos[$i]->image?>" class="<?php echo $photoclass; ?>" alt="<?php echo $photos[$i]->image_desc;?>" title="<?php echo $photos[$i]->image_desc;?>"/>
<?php
}
}
}
?>
That outputs the images correctly, however the "Photo Count" does not increase and thus each photo gets the "First Photo Class" (property_photo_main_1). I fully appreciate that the problem here is because the count is not within the loop to print each photo, but as that is directly before that image output, where is the loop, and how can I implement that the count increases?
The HTML Output is:
<img src="http://msa.eighttwentydesign.com/images/osproperty/properties/5/medium/51384100282240dc03c72cb44ce05eb9e56021d0c05.jpg" class="property_photo_main property_photo_main_1" alt="" title=""/>
<img src="http://msa.eighttwentydesign.com/images/osproperty/properties/5/medium/51384100283f9f748ca556070c2d09553298dc26d8f.jpg" class="property_photo_main property_photo_main_1" alt="" title=""/>
<img src="http://msa.eighttwentydesign.com/images/osproperty/properties/5/medium/51384100283b280e25f329d8cf1518bda4700b07765.jpg" class="property_photo_main property_photo_main_1" alt="" title=""/>
<img src="http://msa.eighttwentydesign.com/images/osproperty/properties/5/medium/51384100283c801f9afb73308c7fd77a77ea00129bb.jpg" class="property_photo_main property_photo_main_1" alt="" title=""/>
</div>
You never increment $photocount outside of that if. Also you never reset $photoclass
foreach ($photos as $photo) {
if (!empty($photo->image)) {
if (JPATH_ROOT.'/images/'.$row->id.'/medium/'.$photo->image) {
if (!isSet($photocount))
$photocount = 1;
else
$photocount++;
$photoclass = "property_photo_main property_photo_main_" . $photocount;
//HTML...
}
}
}
This way $photoclass gets reset in each iteration, also $photocount gets incremented by 1 if it has been set. I also took the liberty of using PHP's internal structures like foreach or empty, you can read about the usage in the manual.
Since JPATH_ROOT.'/images/'.$row->id.'/medium/'.$photo->image has no logic and is not null/false, it will always return true, maybe you meant to use something like file_exists?
Using !$photoclass instead of !isSet($photoclass) will throw an undefined variable notice.

More elegant way of dealing with query string variables

The site I am building is a configurator that lets you choose the color of certain items. It will have functionality to share your color config. What it will do is generate a URL with a query string, like ?plate=red&cup=blue&napkin=white My code reads the query string and changes the <img> src value. For example...
<?php
//This stuff is just grabbing the query string values...
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$querystring = parse_url($url);
parse_str($querystring['query'], $color);
$availableColors = array("red","blue","white");
?>
This is my HTML where I'm using PHP to put in the query string color values. This code is also checking to make sure the color is in an array of the available colors.
<div data-color="<?php if( in_array($color['plate'],$availableColors) ) {echo $color['plate'];} ?>">
<img src="img/tablesetting/<?php if( in_array($color['dinnerPlate'],$availableColors) ) {echo $color['plate']."_plate.png";} else {echo "dummy.gif";} ?>">
</div>
<div data-color="<?php if( in_array($color['napkin'],$availableColors) ) {echo $color['napkin'];} ?>">
<img src="img/tablesetting/<?php if( in_array($color['napkin'],$availableColors) ) {echo $color['napkin']."_napkin.png";} else {echo "dummy.gif";} ?>">
</div>
<div data-color="<?php if( in_array($color['cup'],$availableColors) ) {echo $color['cup'];} ?>">
<img src="img/tablesetting/<?php if( in_array($color['cup'],$availableColors) ) {echo $color['cup']."_cup.png";} else {echo "dummy.gif";} ?>">
</div>
What I'd like to do is avoid having a conditional statement every time I want to check if the color value is in my array availableColors. I guess just a more concise/elegant way of doing this is what I'm looking for.
function getColorData($color, $type) {
$result = array('color_name' => '', 'color_img' = 'dummy.gif');
$available_colors = array('red', 'blue', 'green');
if (in_array($color, $available_colors))
$result = array('color_name' => $color, 'color_img' = $color . '_' . $type . '.png');
return $result
}
Usage example:
$plate_color_data = getColorData($color['plate'], 'plate');
echo '<pre>',print_r($plate_color_data),'/<pre>'; // just for test)
<div data-color="<?=$plate_color_data['color_name']?>">
<img src="img/tablesetting/<?=$plate_color_data['color_img']?>">
</div>
First off, is there a reason you are using parse_url....can't just just grab the variables via $_GET or $_REQUEST?
Secondly, if you want to validate your data in_array is a good approach. A simple thing to clean things up is to simply move it all to your php area and then simply output the post-validated data to the html.
If I were building this I would run all this stuff from a database so you would query to database if a color was valid.
I would also consider generating the graphics server side via imagick or gd.

Displaying an icon and text based on post type in wordpress

I have a defined set of seven different post types and would like to display an icon for each one in the search results list.
I've got the following code to display the post type but have no idea how to extend it into an if
<?php $post_type = get_post_type_object( get_post_type($post) );
echo $post_type->label ; ?>
Any help appreciated.
You can display different icons like this:
<?php
$post_type = get_post_type($post);
switch ($post_type) {
case "type1":
echo "<img src='label1.png'/>";
break;
case "type2":
echo "<img src='label2.png'/>";
break;
}
?>
Even better, if you included post type names in icon filenames, you can simply insert post type in the src attrib in of img tag:
<img src="post_type_<?= get_post_type($post) ?>.png"/>

Categories