How to add a class to all elements when displaying a post? - php

Using the get_posts() method, I get and display the last 5 posts. They are displayed as a slider. Each slide is a different color. Only 3 colors: yellow, green and blue. How can I add a class to each of the 5 slides to give a different background? The first 3 slides should be yellow, green and blue, and the rest should be yellow and green. How can i do this? Now I tried to implement this functionality, but the class on each slide is yellow-slide
My Code:
<?php
$last_posts = get_posts(array(
'numberposts' => 5,
'orderby' => 'date',
'post_type' => 'post',
));
global $post;
$bgcolor = '';
if ($counter == 0) {
$bgcolor = 'yellow-slide';
} else if ($counter == 1) {
$bgcolor = 'green-slide';
} else if ($counter == 2) {
$bgcolor = 'blue-slide';
} else if ($counter == 3) {
$bgcolor = 'yellow-slide';
} else {
$bgcolor = 'green-slide';
}
?>
<div class="swiper">
<div class="swiper-wrapper">
<?php $counter = 0;
foreach ($last_posts as $post) :
setup_postdata($post); ?>
<div class="swiper-slide <?php echo $bgcolor ?>"></div>
<?php $counter++ ?>
<?php endforeach;
wp_reset_postdata(); ?>
</div>
</div>

Your PHP code is executed in the order it's written in, so your if-statements will be executed before you've even started the foreach-loop (and before the variable $counter even exist). It should actually throw a bunch of "Undefined variable: $counter"-warnings/notices.
There is an easier way though.
Put the class names in an array
Fetch the class from the array on each iteration that matches the array index
Something like this:
$bgcolors = [
'yellow-slide',
'green-slide',
'blue-slide',
'yellow-slide',
'green-slide',
];
Then after you've defined that array, you can do:
$counter = 0;
foreach ($last_posts as $post) :
setup_postdata($post);
?>
<div class="swiper-slide <?php echo $bgcolors[$counter] ?>"></div>
<?php $counter++ ?>
<?php endforeach;

Please try this and check again.
<?php
$last_posts = get_posts(array(
'numberposts' => 5,
'orderby' => 'date',
'post_type' => 'post',
));
?>
<div class="swiper">
<div class="swiper-wrapper">
<?php
foreach ($last_posts as $key => $post) :
setup_postdata($post);
$bgcolor = '';
if ($key == 0) {
$bgcolor = 'yellow-slide';
} else if ($key == 1) {
$bgcolor = 'green-slide';
} else if ($key == 2) {
$bgcolor = 'blue-slide';
} else if ($key == 3) {
$bgcolor = 'yellow-slide';
} else {
$bgcolor = 'green-slide';
}
?>
<div class="swiper-slide <?php echo $bgcolor ?>"></div>
<?php endforeach;
wp_reset_postdata();
?>
</div>
</div>

Related

Different layout for nth rows ACF REPEATER

I am using ACF repeater to display images, I want to achieve layout so that 1 - 2 - 3 elements go with col-lg-4 grid and 4-5-6-7 go with col-lg-3 grid and so on, repeating that layout for all items
I've tried using but it's to get 3 elements into 1 div
mostly my layout will be
first row 3x col-lg-4
second row 4x col-lg-3
third row 3x col-lg-4
fourth row 4x col-lg-3
<?php
// check if the repeater field has rows of data
if( have_rows('gallery_repeater') ):
// loop through the rows of data
// add a counter
$count = 0;
$group = 0;
while ( have_rows('gallery_repeater') ) : the_row();
// vars
$teacher_bio = get_sub_field('image');
if ($count % 3 == 0) {
$group++;
?>
<div id="teachers-<?php echo $group; ?>" class="cf group-<?php echo $group; ?>">
<?php
}
?>
<div class="teacher">
<img src="<?php the_sub_field('image'); ?>" />
<?php echo $teacher_bio; ?>
</div><!-- .teacher -->
<?php
if ($count % 3 == 2) {
?>
</div><!-- #teachers -->
<?php
}
$count++;
endwhile;
else :
// no rows found
endif;
?>
Hi Please check below code for reference :
$gallery_repeater = get_field('gallery_repeater');
foreach (array_chunk($gallery_repeater, 7) as $key => $value) {
foreach ($value as $k => $val) {
$class = $k < 3 ? 'col-lg-3' : 'col-lg-4';
echo '<div class="'.$class.'"> <img src="'.$val['image'].'" />'.$val['teacher_bio'].'</div>';
}
}

Create Two Column Related Thumbnails in Wordpress

I want two column related thumbnail like this screenshotI Want To create two-column thumbnail related posts like in screenshot I have linked to:
This is the code so far:
<!---Related Posts --->
<div class="singlerelated">
<div class="headingbig"><div class="shortcode-unorderedlist fa fa-hand-o-right"> Lees meer over <span class="headingorange"><?php the_category(', ') ?></span></div>
</div>
<div class="relatedentry">
<?php
$orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category)
$category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 8,
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
while($my_query->have_posts()) {
$my_query->the_post();
?>
<ul>
<li class="even">
<?php the_post_thumbnail(array(100,100), array('class' => 'relatedthumb')); ?>
<p class="title">
<?php the_title(); ?>
</p>
</li>
</ul>
<?
}
}
$post = $orig_post;
wp_reset_query();
?>
</div>
</div>
<!---Related Posts --->
I want it to be displayed in 2 columns, By Creating li class either even or odd generated alternatively so I can put even class in left side and other in right side. Please Help me.
Try using an $i auto-increment value in your loop. You probably want to do a for with a count and round up incase you have an odd number of posts. May not put an end </ul> on it if you don't do a count. This is the idea though:
$i = 1;
while($my_query->have_posts()) {
$my_query->the_post();
// If $i equals 1, start the <ul>
if($i == 1)
echo '<ul>'.PHP_EOL;
?> <li class="even">
<?php the_post_thumbnail(array(100,100), array('class' => 'relatedthumb')); ?>
<p class="title">
<?php the_title(); ?>
</p>
</li>
<?php
// end on the second loop
if($i == 2) {
echo '</ul>'.PHP_EOL;
// Reset the count back to 0 so it starts
// back at 1 after incrementing
$i = 0;
}
$i++;
}
EDIT To do even and odd, you can use a modulus calculation:
for($i = 0; $i < 10; $i++)
echo (($i % 2) == 0)? 'even:'.$i.'<br />' : 'odd: '.$i.'<br />';

How to add odd and even class in group?

I want to add odd and even class in pairing. So how can i do it with php.
<div class="root">
<div class="odd">
</div>
<div class="odd">
</div>
<div class="even">
</div>
<div class="even">
</div>
</div>
I want to create structure in wordpress post loop.
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 1
);
$html = '';
// The Query
$query = new WP_Query( $args );
if( $query->have_posts()){
while ( $query->have_posts() ) {
}
}
So how can i do it. Please suggest me some ideas.
Use counter to check how many row you have printed and reset it when you want to start over:
<?php
if ($query->have_posts()) {
$count = 0;
while ($query->have_posts()) {
if($count < 2){
// add <div class="odd"> block here
}else{
// add <div class="even"> block here
}
$count++;
if($count == 4){
$count = 0;
}
}
}
?>
Use This
$class = 'even';
echo '<div class="root">';
while ($query->have_posts()) {
$class = $class != 'even' ? 'even' : 'odd';
echo "<div class='{$class}'></div>";
echo "<div class='{$class}'></div>";
}
echo "</div>";

Nested for loop to create 2 HTML rows every 3 items and wrap every 2 rows with an outer HTML wrapper

So basically I am building a wordpress gallery, I need to have the images output into 2 rows, each row is 3 images across so essentially I am just splitting the output every 3..
I have that functionality working with a for loop using the modulus operator, what I need is that every 2 rows I need to have them wrapped in an outer HTML container
<div class="wrappy">
but I cant seem to get this quite right having worked on it most of yesterday, Im not that great at PHP but I understand enough to get by so any help at all would be great... I am using wordpress advanced custom fields for storing the images etc so you can ignore that part, the magic Im working on starts at
<div class="wrappy">
<?php
$rows = get_field('staff_slides', 'options');
$countmax = count($rows) - 1;
//echo $row_count;
$ender = "";
$mainEnder = "";
$outer_wrapper = "";
if( have_rows('staff_slides', 'options') ):
// loop through the rows of data
while ( have_rows('staff_slides', 'options') ) : the_row();
$image_id = get_sub_field('slide_image', 'options');
$staff_members_name = get_sub_field('staff_members_name', 'options');
$staff_members_position = get_sub_field('staff_members_position', 'options');
$staff_image = wp_get_attachment_image_src( $image_id , 'homepage-staff');
?>
<?php
echo '<div class="wrappy">';
echo '<div class="row">';
if( $ender != "script-ended" ) {
for( $i=0; $i <= $countmax; )
{
?>
<div class="staff-img c3">
<div class="staff-caption">
<h3><?php echo $rows[$i]['staff_members_name']; ?></h3>
<span></span>
<h4><?php echo $rows[$i]['staff_members_position']; ?></h4>
</div>
<img src="<?php echo wp_get_attachment_image_src( $rows[$i]['slide_image'], 'homepage-staff')[0]; ?>">
</div>
<?php
if( $i % 3 == 2 )
{
echo '</div><div class="row">';
}
if( $i == $countmax )
{
$ender = "script-ended";
}
if( $i == 6){
$outer_wrapper = "set";
}
$i++;
}
}
?>
<?php
if( $outer_wrapper == "set" ){
echo '</div><div class="wrappy">';
}
?>
You should use the array_chunk function to split the array in smaller arrays.
I'm not familiar with the ACF functions but you can do something like:
<div class="wrappy">
<?php
if( have_rows('staff_slides', 'options') ) :
$slides = array_chunk(get_field('staff_slides', 'options'), 3);
foreach ($slides as $slides_row) :
?>
<div class="row">
<?php foreach ($slides_row as $slide_element) : the_row(); ?>
<div class="staff-img c3">
<div class="staff-caption">
<h3><?php the_sub_field('staff_members_name', 'options'); ?></h3>
<span></span>
<h4><?php the_sub_field('staff_members_position', 'options'); ?></h4>
</div>
<img src="<?php echo wp_get_attachment_image_src( get_sub_field('slide_image', 'options'), 'homepage-staff')[0]; ?>">
</div>
<?php endforeach; ?>
</div>
<?php endforeach; else : ?>
No slides do to show
<?php endif; ?>
</div>
This way you create a multidimensional array, divided in chunks of 3 elements, and iterate throught it.

php array output data using a loop

I'd like to set the following up as a loop (so that the pattern is repeated every 5 elements). I've tried to read up on it and I believe I need to set it up as an array, but I have no idea where to start.
Here's my code:
<div class="ccm-page-list">
<?php
$i= 0;i;
foreach ($pages as $page):
$i++;
$title = $th->entities($page->getCollectionName());
$url = $nh->getLinkToCollection($page);
$target = ($page->getCollectionPointerExternalLink() != '' && $page->openCollectionPointerExternalLinkInNewWindow()) ? '_blank' : $page->getAttribute('nav_target');
$target = empty($target) ? '_self' : $target;
$description = $page->getCollectionDescription();
$description = $controller->truncateSummaries ? $th->shorten($description, $controller->truncateChars) : $description;
$description = $th->entities($description);
$img = $page->getAttribute('thumbnail');
$thumb = $ih->getThumbnail($img, 550, 550, true);
?>
<a href="<?php echo $url ?>" target="<?php echo $target ?>"> <div class="col-sm-4 grid-item">
<div class="item-img-blog" >
<img src="<?php echo $thumb->src ?>" width="auto" height="100%" alt="" />
<div <?php
if($i == 1) {
?>class="item-class-1" <?php }
if($i == 3) {
?>class="item-class-2" <?php }
if($i == 2) {
?>class="item-class-3" <?php }
if($i == 4) {
?>class="item-class-3" <?php }
if($i == 5) {
?>class="item-class-1" <?php }
?>>
<div class="text-container">
<h1><?php echo $description ?></h1>
<p><?php echo $date = $page->getCollectionDatePublic('d/m/Y'); ?></p>
</div>
</div>
</div>
</div></a>
<?php endforeach; ?>
</div>
I would really appreciate any help! Thanks in advance!
$i= 0;
$classes = array(1 => 1, 2 => 3, 3 => 2, 4 => 3, 5 => 1);
foreach ($pages as $page) {
$i++;
.....
echo 'class="item-class-'.$classes[$i % (count($classes) + 1)];
.....
}
You don't need an extra loop, you can use the modulo operator (aka, the remainder of a division) and some basic math to cope with the fact that you want to cycle 1->5:
$i= 0; // note that I removed the "i;" at the end of this line!
foreach ($pages as $page):
$cyclici = ($i % 5) + 1;
// then, use $cyclici everywhere you want to see that 1-5 1-5 pattern
...
if($cyclici == 1) {
...
// and increment $i at the *end* of the loop instead of the start.
$i++
endforeach;
EDITed to clarify the relationship between $i and $cyclici - $i is still incremented for each iteration of the loop, $cyclici is derived from that incrementing value to obtain the desired 1 2 3 4 5 1 2 3 4 5 ... sequence.

Categories