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">';
Related
I have code like this ;
$Photo = filtering($row['FileIcon128']);
<div class="image" style="background:url(/images/imgs/<?php echo $Photo ?>)"></div>
I tried everything
filtering($row['FileIcon128']); , echo ''.$Photo.'';
instead of
$Photo
But i cant get picture. Any idea?
By the way, i have to use
<div class="image"
Give this a shot:
<?php
$Photo = filtering($row['FileIcon128']);
$string = "/images/imgs/" . $Photo;
?>
<div class="image" style="background-image:url('<?php echo $string; ?>')"></div>
Explanation
I saw 3 possible bugs in your code, which were:
1) <?php echo $Photo ?> without a semicolon after $Photo. I don't know if that's a syntax error or not in inline php, however I added the semicolon to make sure and concatenated the static string with the dynamic variable to make for a less messy inline PHP like this: <?php echo $string; ?>.
2) background:url() is not the right way to do this. You want to be as explicit as you can, so background-image:url().
3) background-image:url() without '' (apostrophes) surrounding the parameter passed. background-image:url('') fixed that. I just echoed the code in between the two apostrophes.
I have a php script which randomly needs to show images based on a specific page title.
So I managed to find some code with an if statement, which works with a single image but when I want it to show random images I don't get it to work.
Example of what works:
<?php if(is_page('Page title')){ echo '<img src="/imageA.jpg" />'; } ?>
Example of what I am after:
<?php if(is_page('Another page title')){ echo '<img src="/image-<?php echo rand(B,C; ?>.jpg">'; }
What above needs to do is load randomly imageB.jpg or imageC.jpg
This doesn't happen now because in the url you can see that the code after image- is being rendered wrong, so it can't find the image.
Alternatively, you could map out an array of letters and take use of array_rand() to randomly select letters inside the mapped letters:
<?php
if(is_page('Another page title')) {
$letters = range('B', 'D'); // generates an array of letters B to D, just change it into your liking
echo '<img src="/image-' . $letters[array_rand($letters)] . '.jpg" />';
// take out that `<?php` inside the string, you don't need those
}
?>
Sidenote: That range() function is optional, if you do not want it, just explicitly set what values that you want randomized:
$letters = array('Z', 'X', 'T', 'banner', 'logo', 'header'); // if you don't want that function above
You doing it wrong way. You are trying to insert php code inside a string, which is not going to be evaluated, but rather just outputted as is.
What you have to do, is to select a random image, for example, that way, using array_rand function:
<?php
$images = array('A', 'B', 'C');
$random_image = array_rand($images);
if (is_page('Another page title')) {
echo '<img src="/image-' . $images[$random_image] . '.jpg">';
}
use the string contatination operator - '.' - in order to append additional output (such as a function call) to the string.
<?php if(is_page('Another page title')){ echo '<img src="/image-' . rand(...) . '.jpg">';}?>
What I am trying to do is get an echo of the following php call and subtract 14.1% from the displayed number.
The code:
<?php echo $program->current_amount(); ?>
Can I add arithmetic functions to this in order to display the 14.1% deduction?
I think you're looking for a basic math operation in your output that has no effect on a database or anything else, correct?
If so, do something like the following:
<?php
// Set values
$current_amount = 100;
$pcnt_off = 14.1;
// Do the math
$out = $current_amount - ($pcnt_off/100) * $current_amount;
// Output
echo $out . " is " . $pcnt_off . "% off of " . $current_amount;
?>
http://codepad.org/RqF8cuvN
More specifically to your case:
<?php echo $program->current_amount() - 0.141 * $program->current_amount(); ?>
You can perform expressions inside an echo statement, yes; just wrap it in a (), so:
<?php echo ($program->current_amount() - .141); ?>
It may not even be necessary to use (). Incidentally, if your environment supports short tags, you can simply do:
<?= $program->current_amount() - .141 ?>
Keep in mind, though, that that code won't actually remove 14.1% from your number--you would want to multiply by .859.
I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn't work ?..
echo '<a href="./customer-files/';
echo $customerID;
echo '/';
echo $filename->getFilename();
echo '">';
echo $filename->getFilename();
echo '</a>';
Try with
echo "{$filename->getFilename()}";
Here there is the documentation with a lot of examples of how to concatenate output.
I'd approach it like this:
$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "$safe_label";
I would go with this:
$fn = $filename->getFilename();
$link = $customerID . '/' . $fn;
echo ''.$fn.'';
If you're using a template layer, it is even better to break out into PHP only when you need to:
<a href="./customer-files/<?php
echo $customerID . '/' . $filename->getFilename()
?>">
<?php echo $filename->getFilename() ?>
</a>
This way, your IDE will correctly highlight your HTML as well as your PHP. I've also ensured that all PHP is in single-line blobs, which is the best approach for templates (lengthy statements should be banished to a controller/script).
Concatenation is your friend. Use a . to combine multiple string expression into one.
echo ''.$filename->getFilename()/'';
Even better way would be
$filename = $filename -> getFilename(); //cache the filename
echo "<a href='/$customerId/$filename'>$filename</a>";
// ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.
Ok, it's Wordpress related and I know about Wordpress Stack Exchange, but I'm asking here because this is mostly a PHP question.
I want my code to display something or nothing using if statement.
The problem is I'm going to have a variable and bloginfo('template_directory') in-bulit function.
I wrote this:
<?php if (!empty($instance['example']))
echo "<li><img src="?><?php bloginfo('template_directory') ?><?php echo "/images/example.png /></li>"; ?>
It works fine until $instance['example'] is not empty, when is - it still displays the template directory link including images/example.png.
Any ideas?
I've tried " . bloginfo('template_directory') . " but doesn't seem to work.
PHP if statements that do not have braces { } will only evaluate the first line thereafter. To resolve this,
<?php if (!empty($instance['example'])) {
echo "<li><img src="?><?php bloginfo('template_directory') ?><?php echo "/images/example.png /></li>"; } ?>
Try that and see if it works for your needs. All I did was insert the braces so that your if statement spans all of your arguments.
You forgot to add the : after the if statement to make an if endif; block. Alternatively use the standard curly brackets to enclose all your commands in the if statement.
Currently it's only checking if for the first echo command.
Try this code:
<?php if (!empty($instance['example']))
echo "<li><img src=".get_bloginfo('template_directory')."/images/example.png /></li>";
?>
Try this
<?php if (!empty($instance['example'])) {
echo "<li><a href=". $example ."><img src="?><?php bloginfo('template_directory') ?>
<?php echo "/images/example.png /></a></li>";
}
?>
I'd personally use.
<?php
if( !empty( $instance['example'] ) )
echo '<li><img src="' . get_bloginfo('stylesheet_directory') . '/images/example.png" alt="" border="0" /></li>';
?>
First we add those missing attribute quotes.
Second we use the stylesheet path to ensure it points to the correct location for a child theme.
Third we call get_bloginfo to get a return value for the echo statement.
Fourth, i also added a border="0" to the image, borders aren't usually wanted for an image inside a link and also added an alt tag, because it will at least help pass HTML validation, even if you leave it empty.
Same answer as others, but with better formatted code:
<?php
if(!empty($instance['example']))
{
echo '<li><a href=' . $example . '><img src=' . bloginfo('template_directory') . '/images/example.png /></a></li>';
}
?>
Added brackets, removed unnecessary opening/closing php tags, and converted strings to single quotes since there are no variables or special characters contained within them that need processing.