Set two classes from array - php

I want to change the classes on every third output from a query:
<?php
$style_classes = array('box','box','box no_right_margin');
$style_index = 0;
?>
I set this on the div:
<div <?php $k = $style_index%4; echo "class=$style_classes[$k]"; $style_index++; ?>>
On the third div I want the class to look like this:
<div class="box no_right_margin">
Right now it looks like:
<div class="box" no_right_margin>

You need to enclose the class names in quotes. Your script is actually outputting class=box no_right_margin. (I think the example you gave as the current output is not what the script is sending, but the view of the DOM from something like Firebug, which is showing the browser as only seeing the first class in the list)
So you could do this:
<div class="<?php $k = $style_index%4; echo $style_classes[$k]; $style_index++; ?>">
or even
<div class="<?php echo $style_classes[$style_index++ % 4]; ?>">

You should use %3 instead of %4, so you actually get indexes 0, 1 and 2.
And you need correct quotes in your HTML output:
<?php echo '<div class="' . $style_classes[$k++ % 3] . '">'; ?>
Else your browser (Safari?) would probably correct it with a " at the wrong place, as shown in your example. Btw, it's better style to use hyphens for CSS class names, not underscores (unlike IDs).

Related

display none if php function is empty

I have a wordpress function that displays adverts every so often. When are not shown essentially I would prefer to the div to display:none;
I can not seem to figure out the correct PHP function in order for the div not to display when a advert is uploaded.
<div class="advert" <?php if(!empty($_GET['details'])) {echo "style='display: none'";} ?>></div>
Why not completely not echo "advert" element?
if ( !empty($_GET['details']) ){
echo '<div class="advert">add text</div>';
}
if you really want to just hide, you can assign hide class
<div class="advert <?php echo ( empty($_GET['details'])? 'hide' : '' );">add text</div>
then you would need to add "hide" class with display:none in your style.css
Above is shorthand/ternary if/else statement used, its great if you need output some string.
And, please don't output/trust any user input i.e. $_GET['details'] 'as is' anywhere without escaping it, for security reasons.
Wordpress have plenty easy-to-use escape functions, like esc_attr() and esc_html().
This should do it for you
<?php
$advert_display_string = "";
if (!isset($_GET['details'])) {
$advert_display_string = "style='display: none'";
}
?>
<div class="advert" <?php echo $advert_display_string ; ?> ></div>`
but having said that, instead of displaying it and then hiding it with css, you could just choose only to display it if you need it there, like below
<?php
if (isset($_GET['details'])) {
?>
<div class="advert"></div>
<?
}
?>

Using a php function inside a php echo

I'm trying to setup my WordPress website so that if a post / page has a featured image assigned, this image will be used as the page banner. If however the page doesn't have a featured image, it must onload select a random image out of six available options. I've tried to used this if statement below:
<div id="slider">
<div class="theslide">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
else {
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random = rand(1,6); '.jpg">';
}
?>
</div>
</div>
It works, but the random number function is not closing preperly, so the code ends up looking like this:
<div id="slider">
<div class="theslide">
<img src="/wp-content/uploads/link-ship-chandlers-banner-6 </div>
</div>
</div>
Instead of like this:
<div id="slider">
<div class="theslide">
<img src="/wp-content/uploads/link-ship-chandlers-banner-6.jpg">
</div>
</div>
I'm assuming my syntax is wrong for using php inside of the echo, but everything I try either has the same problem or cause a php error.
Any help would be appreciated.
Thanks in advance
Willem
If you don't need to know which header was chosen, just do this:
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . rand(1,6) . '.jpg">';
Using more than one ; on a line is a no-go (you are essentially telling the php-interpreter that '.jpg">'; is an independant command - which will do nothing)
Assigning a variable (ie. $whatever = 'something) inside the echo statement won't be a problem in this case - though it really doesn't do any good either. What it does is create a new variable called $random that you could use afterwards to find out which header was used - but results will be unpredictable if used in the echo statement (ie. in your case the variable would contain [random number].jpg, not just the random number), instead assign the random number to $random first like this:
$random = rand(1,6);
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random . '.jpg">';
echo "We are using header {$random}, which was chosen at random.";
Note that the above example also shows an alternate way to include the variable in a string - using double-quotes you can simply write the variable directly inside the string itself. When doing so I recommend always using {} to wrap the variable though not needed in this case - this allows referencing more complex variables (such as array elements or object properties), and it makes the whole thing more readable too.
Other (IMO less readable, possibly more error-prone) solutions include:
$random = rand(1,6);
echo "<img src=\"/wp-content/uploads/link-ship-chandlers-banner-$random.jpg\">";
echo sprintf('<img src="/wp-content/uploads/link-ship-chandlers-banner-%d.jpg">', $random);
printf('<img src="/wp-content/uploads/link-ship-chandlers-banner-%d.jpg">', $random);
Actually this can work, but you end the line with ;.
So removing the ; and adding a .
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random = rand(1,6) . '.jpg">';
do this alternatively you don't need to set this variable
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . rand(1,6) . '.jpg">';

Alternate text of div

Can i put class name in title of div? It's possible?
<div class="flag brasileña" title="phpcode"></div>
I want put in title, text of second class "brasileña" with php code or similar
<?php
$className = "flag brasileña";
$alt = explode(" ", $className);
?>
<div class='<?php echo $className ?>' title='<?php echo $alt[1] ?>'></div>
Assuming class name always has two words and alt always take the second word and since you mentioned you want to do it by php the class name is generated dynamically.
This is how you can do it but this wont serve any purpose.
Whats that you want to do with adding second word to "alt".

CSS Class on end MySQL row

I am having trouble creating a solution that will target the end row of a MySQL query. Currently I have a foreach function that works through the query and displays each one as a div with the information inside:
<?php $residents = Resident::find_all();
foreach($residents as $resident): ?>
<div class="submenu">
<p class="menuitem submenuheader"><?php echo $resident->name; ?></p>
<img src="images/<?php echo $resident->image_path(); ?>" width="250" class="image" />
<p><?php echo $resident->info; ?></p>
</div>
.submenu currently has a bottom border. I need to remove this on the last row returned. I have looked at DESC LIMIT 1, however this requires another MySQL query and could make things very messy...
Addd this to your CSS:
.submenu:last-child { border-bottom: 0; }
Note: this is not supported by IE < 9.
You could switch to putting the border on the top of the element, and use the :first-child pseudo selector in CSS to remove it.
http://reference.sitepoint.com/css/pseudoclass-firstchild
The :last-child selector would be nice, but it's not supported in IE before version 9, so it's not a good idea to use it if you want compatibility.
If you separate your HTML and PHP a little this is easily achieved:
<?php
function echoBlock($resident,$pClass="menuitem submenuheader") {
echo "<div class=\"submenu\">\n<p class=\"$pClass\">\n";
echo $resident->name;
echo "</p>\n<img src=\"images/";
echo $resident->image_path();
echo "\" width=\"250\" class=\"image\" />\n<p>";
echo $resident->info;
echo "</p>\n</div>\n\n";
}
$residents = Resident::find_all();
$last=count($residents)-1;//2 element array last pos is 1
for ($i=0;$i<$last;$i++) {
echoBlock($residents[$i]);
}
echoBlock($residents[$last],"menuitem");
?>
echoBlock (which could easily be a method on a class) requires the calling code to know about the classes it uses, which isn't really separating intent but it does prevent the need for an if branch on every loop. That being said it would be less efficient but perhaps more usable to set it up as:
function echoBlock($resident,$isLast=false) {
$pClass="menuitem".($isLast?"":" submenuheader");
//...
Which then doesn't need the caller to know anything about what echoBlock does.
You could try and pop the array using array_pop(), to get the last value out of the array and then inputing it using the special class after the foreach loop.
What about
Instead of echo'ing each line one by one, create one big string in PHP, search for the last entry of "submenu" and change the class.

Numbers & css classes

How can I add a css class to a randomly generated number.
example:
if the number is under 2000 add a css class named red to the div <div class="red">500</div>
if the number is over 2000 add a css class named blue to the div <div class="blue">2500</div>
There are many ways this could be done, but here's one simple one. If $rNum holds your randomly-generated number we can test whether it is less than or equal to 2000. If it is, we'll print "red", and if it's not we'll print "blue".
<p class="<?php print ( $rNum <= 2000 ) ? "red" : "blue" ; ?>">Hello World</p>
If you're new to PHP you may find the syntax of the ternary operator to be somewhat confusion. It's basically a simplified inline if-else statement. You can see more examples and read a short description online at php.net.
you can first generate the rand number, store it into a variable and then use if..else to add the class to div element, like below:
<?php $rand = rand($min,$max); ?>
<div class="<?php if ( $rand <= 2000 ) echo "red"; else echo "blue" ; ?>"><?php echo $rand; ?></div>
Alternatively, add an id element to this div tag, and then use Javascript to add the class.
Do you want to do this?
<div class="<?php echo ($number<2000)?'red':'blue'; ?>">
<?php echo $number ?>
</div>

Categories