Random background images in wordpress? - php

I am using WP 3.5.1, twenty twelve child theme and PHP 5.2 on my server.
I am trying to use a php script(that works on my other websites) in order to get random background-image but it's not working:
CSS:
body {
background: url(<?php include ("bg.php"); echo $selectedBg; ?>) no-repeat fixed;
}
PHP:
<?php
$bg = array('1.jpg','2.jpg','3.jpg','4.jpg','5.jpg');
$i = rand(0, count($bg)-1);
$selectedBg = "$bg[$i]";
?>
my php file is in the same folder as the jpg's.
Any ideas?
No errors. If I use background: url(1.jpg); (instead of php) it works fine but obviously shows 1 image.

Small solution:
We know that he have 5 images on the server:
'1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'
So quick tip:
<body style="background: url('pahttoimages/<?= rand(1, 5) ?>.jpg') no-repeat top center;">

i think the CSS file can't explain your PHP code
try body {
background: url(<?php echo '1.jpg'; ?>) no-repeat fixed;
}

As far as I can see, your code is valid.
Except, you should really write the last line like:
$selectedBg = $bg[$i];
No need for quotes here.
I suspect this is what is causing the error:
my php file is in the same folder as the jpg's. Any ideas?
The background-image needs to be relative to the template-file you are using, not the PHP-file. You script will only work if the images are located in the same folder as the template-slices.
In my WP-installation, I have a template located in /wp-content/themes/mytemplate/ and template-graphics located in /wp-content/themes/mytemplate/images/. If I were to use your script, I would need to preappend /images/ before all the backgrounds in your array.
By the way, you should consider installing Firebug on Firefox and inspect the source. Is the background-name parsed into the template? Does loading the image return a 404 not found-error? Is the location and path correct?
background-image: url(<?php include ("bg.php"); echo $selectedBg; ?>);
background-position: fixed;
background-repeat: no-repeat;

Do this:
// bg.php
<?php
return array(
'1.jpg',
'2.jpg',
'3.jpg'
);
// Wordpress CSS
<?php
$imageUrls = include('bg.php');
$imageUrl = $imageUrls[ array_rand($imageUrls) ];
?>
.someClass {
background-image: url(<?php echo $imageUrl ?>);
}

background: url('<?php $a = array('darkred.jpg','red.gif','pink.png'); echo $a[array_rand($a)];?>');

Related

Css background image name from url variables

I have a landing page where I'd like to split test multiple backgrounds and popup overlays.
In the same folders I have images like 01.jpg 02.jpg etc.
The url will be similar to these:
mywebsite.com?bg=01&ov=01
mywebsite.com?bg=07&ov=10
etc...
I'd like to set a default value in case someone reaches the page with the clean url and also take care of security by allowing only numbers in the filename.
Here's what I have put together (it doesn't work):
<?php
if(isset($_GET['bg']){
$bg = (int) abs($_GET['bg']);
}else{
$bg = '01';
}
if(isset($_GET['ov']){
$bg = (int) abs($_GET['ov']);
}else{
$ov = '01';
}
?>
<style>
body {
background-image: url(<?php echo $bg; ?>.jpg);
background-size: cover;
}
.overlay {
background-image: url(<?php echo $ov; ?>.jpg);
background-size: cover;
}
</style>
Can somebody help me with this?

PHP file_exists method not working as expected

I am trying to set the background of the html body dynamically. Basically if a file exists, use it, otherwise use the default. But it keeps using the default regardless of whether the file exists or not.
<style>
body
{
padding-top: 50px;
background-image: url("<?php
clearstatcache();
if(file_exists("/profile_img/".$profileData["ID"]."_bg.jpg"))
{
echo "/profile_img/".$profileData["ID"]."_bg.jpg?". rand(5, 15);
}
else
{
//echo "/profile_img/".$profileData["ID"]."_bg.jpg?". rand(5, 15);
echo "/profile_img/default.jpg?". rand(5, 15);
}
?>");
background-size: cover;
background-position: 50% 50%;
}
</style>
I have tried using the file (the commented line) and it works. I can not see why this doesn't work
Some issues:
Using / will be absolute, causing it to look in the root directory.
Always check vars are set before using.
All that's changing is the filename, so you can use a ternary, which will reduce alot of that code.
<?php
$background = isset($profileData["ID"]) && file_exists('./profile_img/'.$profileData["ID"].'_bg.jpg')
? $profileData["ID"].'_bg.jpg' : 'default.jpg';
?>
<style>
body {
padding-top: 50px;
background-image: url("/profile_img/<?= $background.'?_='.microtime(true) ?>");
background-size: cover;
background-position: 50% 50%;
}
</style>
If it's still not working:
Check the file actually exists.

PHP Gallery with lightbox, folder import and descriptions from file names

Is there a gallery that have three features:
displays pictures in a lightbox
allows to import tens or hundreds of images at once from a folder
takes descriptions from file names
I have to make it on yesterday :)
I've made my own script together with original Lightbox
http://lokeshdhakar.com/projects/lightbox2/
Decided it will be much faster that way:
<?php
echo str_replace(array('<','>'), array('<','>'),'<table id="galx"><tr>');
$source_dir = 'images/taken/from/here';
$mini_dir = 'mini';
$target_dir = 'imagies/copied/to/there';
$i=0;
$images = array_diff(scandir($source_dir), array('..', '.',$mini_dir));
foreach($images as $image)
{
$filename = pathinfo($image, PATHINFO_FILENAME);
$title = mb_strtoupper(trim(str_replace('_',' ',$filename)));
$s = "<td><a href='$target_dir/$image' data-lightbox='galx' data-title='$title' >"
. "<img src='$target_dir/$mini_dir/$filename.jpg' /><br/>"
. "$title<a/></td>"; //gallery with titles
/*$s = "<td><a href='$target_dir/$image' data-lightbox='galx' >"
. "<img src='$target_dir/$mini_dir/$filename.jpg' />"
. "<a/></td>";*/ //gallery without titles
if (++$i % 5 == 0)
$s .= '</tr><tr>';
$s = str_replace(array('<','>'), array('<','>'), $s); //comment this line if want to paste it as php code
echo $s;
}
echo str_replace(array('<','>'), array('<','>'),'</tr></table>');
?>
Some basic css:
#galx {
width: 650px;
}
#galx td {
text-align: center;
}
#galx a {
display: block;
width: 120px;
font-size: 0.8em;
margin:1px auto;
text-decoration: none;
color: black;
text-align: center;
}
I've used FastStone Image Viewer to batch resize images at once and create miniatures. In app just press F3 to open advanced processing tool.
It just won't work with non-english letters on Windows - PHP bug. It still spoils first non-english letter of file name on Linux, so need to prefix '_' in such cases.
Overall good result - i've hided script somewhere on website and in 1,5 hours generated 6 galleries with ~1,5k pictures, and most of the time was consumed by file processing and copying. Not elegant but effective.

php Preventing dynamically added vertical images from being displayed horizontal

I have this problem with a simple cms I'm working on:
I have a simple php function getting image elements from a specified directory, and printing them to the html
<?php if($row["imgs"] == TRUE){ ?>
<div class="imrow">
<?php
$dir = $row["folder"];
$img = glob($dir."*.{jpg,jpeg,png}", GLOB_BRACE);
$tabing = 3;
$scale = sizeof($img);
for ($i = 0; $i < $tabing; $i++) {
echo '<img src="'.$img[$i].'" alt="image" />';
}
?>
</div><?php }//closing the first if of images ?>
(...)
<?php if($row["imgs"] == TRUE) { ?>
<div class="imrow">
<?php
for ($i = $tabing; $i < $scale; $i++) {
if(!($i % $tabing) && ($i!=0)){echo '</div><div class="imrow">';}
echo '<img src="'.$img[$i].'" alt="image" />';
}
?>
</div>
<?php }//second if closing ?>
The style for images and rows:
.imrow {
display: block;
}
.imrow img {
z-index: 10;
float: left;
height: 100%;
cursor: pointer;
transition: transform .5s ease;
box-shadow: 1px 1px 12px rgb(200, 200, 200);
}
And are laid out using a simple jQuery function
$(".imrow").each(function () { // for every row
var row = $(this); //it gives it a name
var rowW = row.width(); //it seals it's width
var imgW = 0; //it sets a image width variable
var fixH = 600; //and get a fixed amount
row.children().each(function () {
$(this).css("height", fixH); //apply fixed height to element in order to get ratio
imgW += $(this).width(); //get the width of this and
$(this).css("height", "100%");
arr.push($(this).attr("src")); // restore
});
row.css("height", rowW / (imgW / fixH) - 2);
});
The problem here is the fact that some of the added Vertical images, turn out horizontal
Here's how it looks in a folder
And how it turns out in the website:
EDIT: This is a php only issue from what I see, because when I analyze the elements in chrome, the images are flipped by default inside, as you all can see here:
So my first bet goes on glob doing something wrong.
Has anyone experienced it, or knows a way to make glob get everything properly?
Bare in mind that this issue only happens to some of the images, and is not depended on the format of the displayed image.
Any help would be extremely useful
It appears the problem was metadata stored in the images that describe the correct orientation.
There is a image-orientation css property that is supposed to be used to display the image in the correct orientation, but it doesn't seem to be supported in all browsers.
The only other solution at the moment is to edit the image's metadata with a metadata editor or, as you have, to open the images in photoshop and save them.

Changing background images in Wordpress theme

I am using a Wordpress theme and want to make it change the background images automatically. So, I used some PHP code and tried to build it into the website, but something is not working and I cannot figure it out, as I am not very good with PHP.
functions.php:
<?php
$bilder = glob( "images/*.jpg" );
shuffle( $bilder );
$zufall = imagecreatefromjpeg($bilder[0]);
imagejpeg($zufall);
?>
... and simply in CSS of my Wordpress:
body {
background: url('<?php print $zufall ?>') no-repeat center center fixed;
}
But for some reason it just does not show the pictures and I am really off with my wisdom now. :(
Can you help me or tell me the error?
Thank you very much in advance.
This should work - you just need the filename of the image which is in the $bilder array
functions.php:
<?php
$bilder = glob( "images/*.jpg" );
shuffle( $bilder );
$zufall = $bilder[0];
?>
CSS:
body {
background: url('image/<?php print $zufall ?>') no-repeat center center fixed;
}

Categories