Use a variable as an index in a foreach loop - php

I have created a layout using a simple WP loop and Im trying to randomise the images that display in the background of each post in the loop.
My method.
Create a function that contains an array of images that I can call from anywhere in the template.
Call the function for the array before the loop.
Use $i to get the each index in the array thus changing the image.
My array function ( a list of 30 images ):
function randompics(){
$images = array(
get_template_directory_uri().'/images/jobs_large/1.jpg',
get_template_directory_uri().'/images/jobs_large/2.jpg',
get_template_directory_uri().'/images/jobs_large/3.jpg',
get_template_directory_uri().'/images/jobs_large/4.jpg',
get_template_directory_uri().'/images/jobs_large/5.jpg'
);
return $images;
}
My template. So I want the background URL to advance through the index of the array with each iteration.
<?php
$pics = randompics();
$i = 0;
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
?>
<div class="col-md-4">
<div class="item-container" style="background: url(<?php echo $pics[$i]; ?>);">
</div>
</div>
<?php
$i++;
endwhile;
endif;
?>
EDIT FOR CLARIFICATION OF MY QUESTION.
My question therefore is why is the background URL not working. The syntax is clearly wrong.

There is nothing wrong with the loop except that you should check array item using "isset($pics[$i])" because if there are x number of images and x+n number of posts then you will get an exception (http://php.net/manual/en/class.outofboundsexception.php) as there is no element at $pics[x].
Your "background" CSS property is wrong. Either use
background-image: url(YOUR IMAGE URL);
or
background:<background-color> <background-image> <background-repeat> <background-position>;
For example,
background:transparent url(YOUR IMAGE URL) no-repeat 0 0;

Related

Count of posts within WP Loop not counting posts to use for div class

I've successfully been able to count the number of posts within a loop before, but for some reason this time it won't work.
<?php $count = 0; if (have_posts () ) { while (have_posts()) { the_post(); $count++; ?>
<div class="post-<?php echo $count; ?>"></div>
<?php } } ?>
Anything Im missing?
UPDATE
After talking to #FlashThunder about this problem. it seems that putting the beginning of the loop in the home.php template and using get_template_part() for the posts that are to be counted won't work unless they are in the same template, otherwise we would need to use global $count. After putting all of the php in the same template, the posts counted and applied the numeric class to the div's like I wanted.

Jump back in Wordpress loop to change something, possible?

Example:
We got some nice posts that got a link to jump to the next post with scrolling down the page. No reload, new tab or anything just a simple smoothscrolling of the page.
Problem:
We are inside a Wordpress Loop that creates some content from the DB and want to generate a link that jumps to the next run-through that will be generated by the Loop. Within the loop we cant predict what will be the next post/product or whatever post-type the loop should go through. So how am I giving the Link the correct anchor link?
Possible Solutions:
Maybe we can store the data from each run in an array?
Maybe we should create a second loop that only saves the data?
Maybe I should just use JS to rename that anchors after it finishes...
You can add an incremental id with the loop index and assign the anchor to the current index + 1. A simple example:
<?php
global $wp_query;
$args = array(
'post_type' => 'post'
);
$post_query = new WP_Query($args);
if($post_query->have_posts() ) {
while($post_query->have_posts() ) {
$post_query->the_post();
$index = $wp_query->current_post + 1;
?>
<div id="my_post_<?php echo $index; ?>"><?php the_title(); ?></div>
<?php
if (($wp_query->current_post +1) <= ($wp_query->post_count)) {
echo 'Next post';
}
?>
}
}
?>

PHP foreach over uniquely styled divs

I'm trying to pull information from instagram and twitter, and display the information as a collection of square and rectangle boxes arranged on screen.
I was using a foreach statement to display the content, but because the containing divs are not consistent in size, I have to end the foreach statement and start a new one. The content of the new foreach is exactly the same as the content of the previous. I'm not sure if I'm going about this the right way and would appreciate any push in the right direction.
The block of code below displays the first 4 most recent instagram photos.
<?php $i = 0; foreach ($instagram_data->data as $latest_post): if (++$i == 5) break; ?>
<div class="engage-block"><img src="<?= $latest_post->images->standard_resolution->url ?>"></div>
<?php endforeach ?>
After that, I display the latest twitter content.
<div class="engage-horizontal engage-block"><span>"<?php echo $latest_tweet->text ?>"</span></div>
And then I repeat another foreach similar to the first to display more instagram content. This however repeats the exact same content from the code above (shows the latest 4 photos instead of the 4 photos after the original photos).
You could put a variable in the foreach to make the twitter div if it's the fifth, like this
<?php
$i = 0; foreach ($instagram_data->data as $latest_post){
?>
if ($i==5){?>
<div class="engage-horizontal engage-block"><span>"<?php echo $latest_tweet->text ?>"</span></div>
$i=0;
}
else{?>
<div class="engage-block"><img src="<?= $latest_post->images->standard_resolution->url ?>"></div>
<?php
}
$i++;
} ?>

Looping through an array in Wordpress

I have created a custom post type with an image gallery upload. Now I am trying to display the gallery on the front end. This is what I have so far that works to display 1 image, but if multiple images are uploaded all the urls get stuck in the src tag. So I'm guessing I should loop through that array and spit out each one separately? Would that be the route to go and if so how can I accomplish this? Any help is appreciated.
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
echo '<img src="'.get_post_meta($post->ID, 'gallery-upload', true).'">';
?>
<?php endwhile; else: ?>
<p><?php _e('No posts were found. Sorry!'); ?></p>
<?php endif; ?>
EDIT:
This is what is being returned:
<img src="http%3A%2F%2Flocalhost%3A8888%2Fandreasmoulis%2Fwp-content%2Fuploads%2F2012%2F10%2F800x400-volbeat-mock1.jpeg%2Chttp%3A%2F%2Flocalhost%3A8888%2Fandreasmoulis%2Fwp-content%2Fuploads%2F2012%2F10%2F1574_2_1.jpeg%2Chttp%3A%2F%2Flocalhost%3A8888%2Fandreasmoulis%2Fwp-content%2Fuploads%2F2012%2F10%2F1576_2_1.jpeg%2Chttp%3A%2F%2Flocalhost%3A8888%2Fandreasmoulis%2Fwp-content%2Fuploads%2F2012%2F10%2F1576_4_1.jpeg%2Chttp%3A%2F%2Flocalhost%3A8888%2Fandreasmoulis%2Fwp-content%2Fuploads%2F2012%2F10%2F2244_2_1.jpeg%2Chttp%3A%2F%2Flocalhost%3A8888%2Fandreasmoulis%2Fwp-content%2Fuploads%2F2012%2F10%2F300789_2349086884438_1168050047_32154880_1451576942_n.jpeg%2Chttp%3A%2F%2Flocalhost%3A8888%2Fandreasmoulis%2Fwp-content%2Fuploads%2F2012%2F10%2F373795_278881222158106_278880528824842_834930_1454244548_n.jpeg%2Chttp%3A%2F%2Flocalhost%3A8888%2Fandreasmoulis%2Fwp-content%2Fuploads%2F2012%2F10%2F20110909-121141.jpeg">
Looking at the function reference, get_post_meta ordinarily returns an array unless the third argument is set to true. Something like this should work, more or less.
<?php
foreach(get_post_meta($post->ID, 'gallery-upload') as $meta) {
foreach(explode(',', $meta) as $src) {
echo '<img src="'.htmlentities($src).'">';
}
}
?>
EDIT: Apparently gallery-upload is stored as comma-separated values. Updated my snippet above to hopefully account for this.

Total image widths in while

I have some php code which echos the width of a specific image size in WordPress. Currently, if the image width is greater than 80, then it echos "frog"...what I would like it to do is count all of the image widths within my while and if the total of those images are greater than 600 (hypothetical number) then echo "frog". The code I am using looks like (I am using this code within my while):
<?php
$image = wp_get_attachment_image_src (get_post_thumbnail_id($post_id), 'gallery-thumbnail');
list($width) = getimagesize($image[0]);
echo $width;
if( $width > 80 ) {
echo "frog";
}
?>
My while is the basic WordPress standard:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<!-- some code here -->
<?php endwhile; else: ?>
<!-- some code here -->
<?php endif; ?>
Any ideas?
Thanks, Josh
Part pseudo code/part solution:
$sumOfWidths = 0;
foreach($images as $image)
{
$sumOfWidths = $sumOfWidths + $image['width'];
}
if($sumOfWidths>600)
{
echo 'frog';
}
Simply put the above code loops through each image and adds the image width to the $sumOfWidths variable.
After the foreach loop, has completed, there should be a number in the $sumOfWidths which you can check and then undertake your logic as you see fit.
Have a look at this code snippet to get you started

Categories