Randomize Header Background On Page Refresh - php

I have looked through a couple of threads, with no luck to this problem. I'm just trying to have different images appear on a new page load for the homepage only. The CSS element I'm trying to change is
.header_container
The html tag is this:
<header id="masthead" class="site-header header_container" role="banner">
I have three images that I would like to rotate in. I have tried to call a php file that calls the images from /images/ and that didn't work.
Here is the site ---> http://www.l4sb.com
Thanks for any help you might have.

Why not store available image paths in PHP array like:
$aBgImages = array('img01.jpg','img02.jpg');
Then add a a <script> tag with something like:
var myElem = document.getElementById['header'];
myElem.style.backgroundImage="url('<?php echo array_rand($aBgImages) ?>')";
The above is not tested, just a rough example.

Related

WordPress ACF Random image from Repeaterfield

I have created a repeater field called: "random_images".
It contains the subfields: "random photo one" (to five)
One random image at the time from these five should be displayed on my front-end. The images should change accordingly: When the page loads, one random image should be displayed. After a couple of seconds, the image should change to another.
How do I do it?
I am new to ACF and PHP. This is what I have come up with so far:
if (get_row_layout() == 'random_images') {
$rows = get_sub_field('random_images');
$rand_row_image = array_rand($random_images, 1);
$image = wp_get_attachment_image_src($rand_image, 'full');
}
I'm going to assume you have a repeater field called random_images that has a repeatable subfield (image field) called image, so, when you go to your post editor (or wherever you place the repeatable field), you can repeat the image field as many times as you want and put as many images as you want there.
Then, if you put your code in single.php (or you template parts or other template files), you can do this:
<?php
// ... template code already there
$random_images = get_field('random_images');
//The line below will mix the array randomly, so you always pick a random element from it
shuffle($random_images);
$random_img_url = $random_imges[0]['image']['url'];
?>
Note: How to get the URL might change depending on how you configured your fields when you created them, but that is the idea.
Note: If you want to use get_field() outside the loop, you are going to have to use the post id in this way get_field('random_images', $post_id);
The code above will give you one of the images you placed in the repeater field, so now you can render that image in you page or post, and the image will be different in every page load.
<img src="<?php echo $random_img_url; ?>" />
To this point, you used PHP to render a random image but with PHP you can't change the image after the page is loaded, so you will have to use jQuery for that (you can use vanilla JavaScript but to make things easy I will explain this with jQuery).
If you don't have a custom file to put JS code in the theme you are developing, then you will have to create a file called custom.js or whatever name you want to give it, and then enqueue that file with wp_enqueue_script. I will not explain more of this because it is not directly related to the question.
Now you have your custom.js file, but you will need a way to get the other image URLs from the page with your random images, so, to achieve that, you can do the following just where we left the php code above.
<?php
$rand_imgs_urls = [];
foreach($random_images as $image) {
$rand_imgs_urls[] = $image['image']['url'];
}
// Now, instead of the <img /> tag we used above, we will use this
?>
<div class="random-img" data-images="<?php echo json_encode($rand_imgs_urls); ?>">
<img src="<?php echo $rand_imgs_urls[0]; ?>" />
</div>
Once you rendered the image, now you can use jQuery to get the images placed in the data-images attribute of the div above, and change the image src every few seconds. So, in the custom.js file you can put something like this:
jQuery(document).ready(function($) {
var images = JSON.parse($('.random-img').data('images'));
var randomImage = images[Math.floor(Math.random()*images.length)];
setInterval(function(){ $('.random-img img').attr('src', randomImage); }, 5000);
});
With that you will have the image changing every 5 seconds.

Embed iframe into a php file

I recently started a new position as a graphic designer for a local nonprofit. I have a little background in HMTL and CSS, but their website runs on PHP and I'm already struggling to work with the code.
I need to add an inline frame to embed a webpage within a specific page on our website. The programmers who built our site didn’t build a user friendly interface where we can embed HTML, so I'm told that I need to add the iframe snippet into the PHP for that page. However, the page I want to edit does not have it's own PHP file. It is a subpage under one of the site's main nav categories. I was able to find a PHP file which corresponds to that main nav category that this subpage falls under. I believe that this is where I would need to add the code. It appears to be a template which structures all of the pages inside of this broader nav category.
Can anyone help me with this? I'm not sure if you can just add HTML to a PHP file as is, or if it needs to be altered a bit. Also I need to know how I could have the PHP template selectively load the desired iframe only on the page that actually needs it - I don't want that iframe to appear in all the other pages that fall within the broader nav category.
The code I need to embed looks like this:
<iframe width="100%" height="800px" src="https://google.com" frameborder="0" scrolling="yes"></iframe>
you can use html as it is on php page.
point 2: you want to show iframe on specific page only...
e.g. on page xyz.php
<?php
$basename = basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */
if ($basename == 'xyz.php'){ ?>
<iframe width="100%" height="800px" src="https://google.com" frameborder="0" scrolling="yes"></iframe>
<?php } ?>

How to display a text file hosted on another server inside a Blogger post

I need to read a text file on a server and display its content in a blog post on Blogger. The text file is a result of a simple download counter and contains a number. The problem is the Blogger does not support PHP codes in a post. My current solution is to use OBJECT tag to call PHP script that displays the text file content with ECHO. It works. But the result is displayed inside a small frame and I can't apply CSS style to it or align it properly with the existing text. Is there another way? I understand it can be done with AJAX call but my scripting knowledge is basic and I wouldn't know where to begin. Help would be appreciated.
To display the result in the blog I used this code:
<p>File test.zip downloaded
<object type="text/plain"
data="http://example.com/statistics.php?dname=test"
width="30" height="30"></object> times</p>
EDIT: I have tried to follow #Toni suggestion but it only leads to more questions. Looks like Ajax call is way beyond my current level of knowledge. Sorry and thank you again.
Here is what I'm currently trying. I have moved the text that goes with the counter inside PHP file so the script now returns a string like "file has been downloaded 8 times" instead of just number "8". Also instead of OBJECT tag I'm using IFRAME.
<iframe src="http://example.com/mystats.php?dname=test"
frameborder="0" border="0" cells pacing="0" height="30"></iframe>
The iframe seems to be easier to style. If I can't figure out how to find which CSS is applied to a blog post and how to apply it to iframe, I can at the minimum mimic the style by using similar font.
You can use javascript with your blogger web-site.
Using javascript on your web-page, you can invoke a GET request to your PHP code and get the data you want, to display it on your web-page.
Below, there are links, to help you with this task:
How to invoke GET request in vanilla JavaScript
Invoking GET with jQuery
Use JavaScript to alter text dynamically
I made it work with JavaScript! Here is how. Server side PHP script reads and echoes a text file inside document.write().
<?php
$varcontent = #file_get_contents('yourtextfile.txt');
echo 'document.write("'.$varcontent.'")';
?>
The resulting string looks like this:
document.write("your text file content here")
Inside the Blogger post add the JavaScript code with the PHP script file as a source:
<script type="text/javascript"
src="http://example.com/yourfile.php">
</script>
Done! The content of your text file is displayed and styled with your current CSS.

Preloading pictures for refresh, cache

I have these two php variables: $img1src and $img2src, (them being PHP is irrelevant as you can echo a php variable anywhere) they both hold a URL of an image. I was wondering if I was able to preload these images, or cache them.
My goal is: when someone refreshes the page I want these pictures to instantly appear in a <img src >.
I'm not going to provide specific code, because I don't want to give you a fish, but rather show how google is a fishing pole.
I googled "php cache images tutorial" just to see what would come up. Below is a great resource.
http://dtbaker.com.au/random-bits/how-to-cache-images-generated-by-php.html
Can't get much better than that.
Caching an image isn't really a job for PHP. PHP should be used to decide whether or not to display it. (There are caching things you can do with PHP, but not in the same sense.) Essentially, what you want to do is make the clients browser request the second image. Once the browser gets the image, it should automatically send an "if-modified-by" parameter in the header. Next time you load the page, the response code should be 304 and your image should load instantly. You can choose from a variety of ways to do this. Load the image with javascript after the page has loaded (to prevent additional load time) or you can just include an image tag that is hidden on the page some where.
I also haven't tested it, but you might be able to send an ajax request to the image directly. I'm not sure if that way would cache it or not.
EDIT:
This isn't the most elegant solution, but it should get the idea across.
JS Example:
<?php
session_start();
if (!isset($_SESSION['graphic'])) $_SESSION['graphic'] = "http://www.tomsfreelance.com/laptop/DSC_0011.JPG";
else $_SESSION['graphic'] = "http://www.tomsfreelance.com/laptop/DSC_0012.JPG";
?>
<html>
<head>
<script>
function loadImage() {
document.getElementById('preload').style.backgroundImage = "url(http://www.tomsfreelance.com/laptop/DSC_0012.JPG)";
}
</script>
</head>
<body onload="loadImage();">
<div id="preload" style="display: none;"></div>
<img src="<?php echo $_SESSION['graphic'];?>">
</body>
</html>
Sure you can, try this javascript:
var image1 = new Image(), image2 = new Image();
image1.src = <?php echo $img1src; ?>;
image2.src = ?<php echo $img2src; ?>;
That should preload the image so when you append an img tag to the DOM the image should appear right away.
If your aim is to make less http requests overall: you can try CSS Sprites and/or Data Url methods of displaying these images. These methods will be the most effective when the images are smaller.

Drupal 6: different slideshows for every page, easy in-node editing for end user

new to Drupal 6. I see a lot of slideshow modules out there, but it seems like most of them require quite a lot of configuration, and would be cumbersome for the user to change later. Some of my pages have sliders, and others have single images in the same spot. I don't want to have a separate node for each slider. The client can't handle that. I would like to have the images uploaded via the attachment section in the page itself, and fields for the image title and alt text. Then I would want to take that and display the image along with the title and alt text as a slideshow, with buttons to switch to previous and next. Is it possible to do this?
The jquery slideshow module almost does what you want, but it doesn't have the next/previous buttons.
I'd recommend just finding a javascript slideshow product that you want to use, and then manually integrate it into a node template.
Recently, I integrated jqFancyTransitions into a Drupal 6 project. The content type contains a image field, set to allow multiple values.
I installed the library in my theme, then, in the content type specific node template, I added this:
mycontenttype-node.tpl
<script src="/sites/all/themes/mytheme/jqFancyTransitions.1.8.min.js" type="text/javascript"></script>
<div id='ft'>
<?php foreach ($node->field_my_photo_field as $image): ?>
<img src="/sites/default/files/imagecache/my_photo_imagecache_preset/<?php print base_path() . str_replace(' ', '%20', $image['filepath']); ?>" alt="" />
<?php endforeach; ?>
</div>
<script>
$('#ft').jqFancyTransitions({ width: 350, height: 300, navigation: true, effect: 'wave' });
</script>
Note, I'm using an imagecache preset to crop & scale the images to 350x300, and I had to str_preplace spaces because jqfancytransitions didn't like them. That's only because it was an easier solution than either requiring users not to use spaces or modifying their file names.

Categories