wrap first post in different div with array_chunk - php

Im adding every 2 posts in a div, but i also want to get the first post in a different div like this:
<div class="first">
<h2>Post title</h2>
</div>
<div>
<h2>Post title</h2>
<h2>Post title</h2>
</div>
<div>
<h2>Post title</h2>
<h2>Post title</h2>
</div>
Here is my code:
<?php
$count = 5;
$args = array(
'cat' => $mag_cat,
'post_type' => 'post',
'post__not_in' => get_option( 'sticky_posts' ),
'posts_per_page' => $count
);
$posts = get_posts( $args ); ?>
<?php foreach ( array_chunk ( $posts, 2, true ) as $posts) :
if ( $posts == 0 ) {
echo '<div class="first">';
} else {
echo '<div>';
}
foreach( $posts as $post ) : setup_postdata($post); ?>
<h2>
<?php the_title(); ?>
</h2>
<?php endforeach; ?>
</div>
The class .first does not seem to print, what I'm a doing wrong?

array_chunk does not allow you to make the first chunk smaller than the rest. Besides this, it is unclear to me why you would compare the value (an array) against an integer.
An inefficient way of accomplishing what you want is by using array_merge and array_slice:
foreach(array_merge([[$posts[0]]], array_chunk(array_slice($posts, 1), 2)) as $key => $value) {
if( $key === 0 ) {
echo '<div class="first">';
} else {
echo '<div>';
}
}
You would probably be better off doing this though, with the appropriate boiler plate around it:
if(have_posts()) {
the_post();
get_template_part('parts/post', 'first');
while(have_posts()) {
the_post();
get_template_part('parts/post');
if(have_posts()) {
the_post();
get_template_part('parts/post');
}
}
}
or even
if(have_posts()) {
the_post();
get_template_part('parts/post', 'first');
while(have_posts()) {
for($i = 0; $i <= 1; $i++ ) {
if(have_posts()) {
the_post();
get_template_part('parts/post');
}
}
}
}

Related

How show 2 categories in 1 loop, PHP(WordPress)

I would like to show like below in HTML with PHP.
It assumes there are six categories.
<div class='box'><p>category 1</p><p>category2</p></div>
<div class='box'><p>category 3</p><p>category 4</p></div>
<div class='box'><p>category 5</p><p>category 6</p></div>
However, I don't know how I do it with PHP.
I did below, but it shows only category 1&2.
<?php $categories = get_categories();foreach ($categories as $category):?>
<div class="sheif"><!-- genre 1 -->
<div class="sheif__inner">
</div>
<div class="sheif__body">
<?php $categories = get_categories(); $x=1; $num=3; foreach ($categories as $category): ?>
<?php if( $x>=$num ) { break; } else { ?>
<div class="sheif__book">
<a href="<?php echo esc_url(get_category_link($category->term_id)); ?>" class="book-btn">
<img src="<?php echo z_taxonomy_image_url($category->term_id); ?>" alt="本">
</a>
<a href="<?php echo esc_url(get_category_link($category->term_id)); ?>" class="bar-genre">
<p><?php echo $category->name; ?></p>
</a>
</div>
<?php } $x++ ; ?>
<?php endforeach; ?>
</div>
<div class="sheif__side-bar">
<p>ジャンルメニュー</p>
</div>
</div><!-- genre 1 -->
<?php endforeach; ?>
Please teach me how it works I want.
You can follow the example below.
$categories = array("category1", "category2", "category3", "category4");
foreach (array_chunk($categories, 2) as $chunk) {
echo "<li>" . implode(', ', $chunk) . "</li>\n";
}
This will output the two value side by side. Array_chunk is a php function that splits an array into chunks, once you get that result you can output it any way, here for example using lists but you can change it to paragraphs.
https://www.php.net/manual/en/function.array-chunk.php
You can use array_chunk to split an array into different groups & run your loop on this group to make it work.
foreach (array_chunk(get_categories();, 2) as $group) {
//render item
foreach ($group as $item) {
<div class='box'><p>$item[0]->name</p><p>$item[1]->name</p></div>
}
}
Try this wp_get_post_categories( int $post_id, array $args = array() ) wp_get_post_categories
$post_categories = wp_get_post_categories( $post_id, array( 'fields' => 'all', 'number'=>'2' ) );
if( $post_categories ){ // Always Check before loop!
foreach( $post_categories as $c ){
//your code here
}
}
OR use get_terms( array|string $args = array(), array|string $deprecated = '' ) get_terms
$terms = get_terms( array(
'taxonomy' => 'taxonomy_name',
'hide_empty' => false,
'number' => 2
) );

Exclude duplicated posts from wordpress using index.php with tempates part

I'm trying to avoid duplicates posts in one file - index.php where i do collection of the loops for categories. But no result. Please - help...
<div class="container-fluid newgray">
<div class="container asia travel-news proppad">
<?php get_template_part( 'inc/slider-news' );?>
</div>
</div>
<div class="container-fluid best">
<div class="container travel-news proppad">
<?php get_template_part( 'inc/best' );?>
</div>
</div>
<div class="container-fluid newback over">
<div class="container last travel-news proppad">
<?php get_template_part( 'inc/latest' );?>
</div>
</div>
Trying use this code:
<?php
$do_not_duplicate = array(); // set befor loop variable as array
// 1. Loop
query_posts('ca=1,2,3&showposts=5');
while ( have_posts() ) : the_post();
$do_not_duplicate[] = $post->ID; // remember ID's in loop
// display post ...
the_title();
endwhile;
?>
<?php
// 2. Loop
query_posts( 'cat=4,5,6&showposts=15' );
while (have_posts()) : the_post();
if ( !in_array( $post->ID, $do_not_duplicate ) ) { // check IDs
// display posts ...
the_title();
}
endwhile;
?>
But it works only when all loops in one php file…
This is How I wold do, don't waste your time repeating same code, it will be a hell if you need change something.
function post_by_cat_ecluding($cats, $per_page, $exclude = array()) {
$html = '';
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category__in' => $cats,
'posts_per_page' => $per_page,
'post__not_in' => $exclude,
'offset' => 0
);
$loop = new WP_Query($args);
foreach ($loop->posts as $p) {
$exclude[] = $p->ID;
$html .= '<article><h2>'.$p->post_title.'</h2></article>';
}
return array('html' => $html, 'exclude' => $exclude);
}
$first_block = post_by_cat_ecluding(array(1,2), 5);
echo $first_block['html'];
$second_block = post_by_cat_ecluding(array(4,5), 15, $first_block['exclude']);
echo $second_block['html'];

PHP Loop: Bootstrap Slider Add div with item class every 3 item and the first one will have active

The current code that I have is rendering additional div. Can you help me how to make it right?
Every 3 items it will be inside a div with item class on it and the first item will have active class.
<!-- Carousel items -->
<div class="carousel-inner">
<div class="item active">
<div class="row">
<?php
$args = array(
'post_type' => 'product',
'product_cat' => 'Featured',
'posts_per_page' => 12
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
$postcount = 0;
$i = 1;
while ( $loop->have_posts() ) : $loop->the_post();
$postcount ++;
?>
<div class="col-md-4 item-entry-index">
<div class="car-index">
<img src="<?php echo get_the_post_thumbnail_url($loop->post->ID); ?>" class="img-responsive" alt=""/>
</div>
</div>
<?php
if ( $i % 3 === 0 ) {
echo '</div></div><div class="item"><div class="row">';
}
?>
<?php
$i++;
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</div>
</div>
</div><!--.carousel-inner-->
As far as I understand your code, you display 12 posts per page. When you display the 12th (the last) post (which is divided by 3), you close .item and .row divs. At the same time, you open new .item and .row divs. Just after that while loop ends and your last post will look like: <div class="item"><div class="row"></div></div>. That's where the problem comes up. So, you also need to check if the post is the last item in posts array. I extended your if statement like: if ($i % 3 === 0 && $i < $args['posts_per_page']) { ... }. I hope this will help you.
<!-- Carousel items -->
<div class="carousel-inner">
<div class="item active">
<div class="row">
<?php
$args = array(
'post_type' => 'product',
'product_cat' => 'Featured',
'posts_per_page' => 12
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
$postcount = 0;
$i = 1;
while ( $loop->have_posts() ) : $loop->the_post();
$postcount ++;
?>
<div class="col-md-4 item-entry-index">
<div class="car-index">
<img src="<?php echo get_the_post_thumbnail_url($loop->post->ID); ?>" class="img-responsive" alt=""/>
</div>
</div>
<?php
if ( $i % 3 === 0 && $i < $args['posts_per_page']) {
echo '</div></div><div class="item"><div class="row">';
}
?>
<?php
$i++;
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</div>
</div>
</div><!--.carousel-inner-->

How to add class to certain items in a loop php?

Hi I'm fairly new to PHP and I'm have a problem adding a class to a group of three items in a loop. So basically I need items 1-3 int the loop to not have the class, items 4-6 to have the class, items 7-9 to not have the class, items 10-12 to not have the class and so on. I know I need to add a counter but I'm not sure how to write the if statement.
Any help is appreciated. Thanks in advance!
Sorry Here is an example of the code
global $wp_query;
$wp_query = new WP_Query( $args );
if( $wp_query->have_posts() ):
while( $wp_query->have_posts() ): $wp_query->the_post(); global $post;
echo '<article class="recipe">
<div class="recipe-img">'.get_the_post_thumbnail( $id, 'featured').'</div>
<div class="recipe-info">
<span>'.get_the_date().'</span> | <span>'.get_the_author().'</span>
<a href="'.get_permalink().'">
<h3 class="lato">'.get_the_title().'</h3>
</a>
</div>
</article>';
}
endwhile;
genesis_posts_nav();
endif;
I was able to do this but It only adds the class to every third item.
$args = array(
'post_type' => 'recipes',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page'=> '3',
'paged' => get_query_var( 'paged' ),
);
global $wp_query;
$wp_query = new WP_Query( $args );
if( $wp_query->have_posts() ):
$count = 0;
while( $wp_query->have_posts() ): $wp_query->the_post(); global $post;
$count++;
if ($count % 3 == 0 ) {
echo '<article class="recipe third">
<div class="recipe-img">'.get_the_post_thumbnail( $id, 'featured').'</div>
<div class="recipe-info">
<span>'.get_the_date().'</span> | <span>'.get_the_author().'</span>
<a href="'.get_permalink().'">
<h3 class="lato">'.get_the_title().'</h3>
</a>
</div>
</article>';
} else {
echo '<article class="recipe">
<div class="recipe-img">'.get_the_post_thumbnail( $id, 'featured').'</div>
<div class="recipe-info">
<span>'.get_the_date().'</span> | <span>'.get_the_author().'</span>
<a href="'.get_permalink().'">
<h3 class="lato">'.get_the_title().'</h3>
</a>
</div>
</article>';
}
endwhile;
genesis_posts_nav();
endif;
<html>
<head>
<title>Counter Colors</title>
<style type="text/css">
span{display: inline-block;padding: 10px;border:solid 1px #ccc;}
.green{color: green;}
</style>
</head>
<body>
<?php
//phpinfo();
$class = 'class="green"';
$put_class = 1;
for ($i=1; $i <= 12 ; $i++) {
if($put_class == 1){
echo '<span '.$class.'>'.$i.'</span>';
} else{
echo '<span>'.$i.'</span>';
}
if($i%3 == 0){
if($put_class == 0){$put_class = 1;}
else{$put_class = 0;}
}
}
?>
</body>
</html>
Just add some extra control to your counter and alter your if statement a bit:
...
while( $wp_query->have_posts() ): $wp_query->the_post(); global $post;
$count = $count > 6 ? 1 : $count + 1;
if (($count > 3) && ($count <= 6) ) {
echo(...);
...

How to output thumbnail twice in a WordPress loop

ok I have a portfolio page. Every portfolio item has thumbnail attached. what I want is to print out the first thumbnail from the first post twice. One at the beginning & other at the ending. like: image_1, image_2, image_3, image_4 & then image_1 again.
my code is:
<div class="main-interior portfolio" id="portfolio-big-pics" style="display: block;">
<?php $args = array( 'post_type' => 'portfolio', 'order' => 'dsc');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $extraFirstClass = $loop->current_post == '0' ? ' main-image-porfolio-main' : ''; ?>
<?php
$attributes = array(
"class" => "main-image portfolio " . $extraFirstClass,
"id" => "photo_{$post->ID}",
);
the_post_thumbnail("portfolio_thumb", $attributes);
?>
<?php endwhile; ?>
<?php rewind_posts(); ?>
<div class="portfolio-box">
<h5>Portfolio</h5>
<ul class="item-list" id="portfolio-list">
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li><?php the_title(); ?>
</li>
<?php endwhile; ?>
</ul>
</div>
</div>
How can I do it?
As previously answered by me here, I would use PHP for. However, if for some reason you don't want that, I don't think you would need to resort to two loops for this. You can do the following:
<?php
$args = array( 'post_type' => 'portfolio', 'order' => 'dsc');
$loop = new WP_Query( $args );
$first = $loop->posts[0];
$attributes = array(
"class" => "main-image portfolio",
"id" => "photo_{$loop->posts[$i]->ID}",
);
<div class="main-interior portfolio" id="portfolio-big-pics" style="display: block;">
for( $i = 0; $i < count($loop->posts); $i++ ) {
$attrs = $attributes;
$attrs["class"] .= $i === 0 ? ' main-image-portfolio-main' : '';
echo get_the_post_thumbnail( $loop->posts[$i]->ID, "portfolio_thumb", $attrs );
}
echo get_the_post_thumbnail( $first->ID, "portfolio_thumb", $attrs );
?>
<div class="portfolio-box">
<h5>Portfolio</h5>
<ul class="item-list" id="portfolio-list">
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li>
<?php the_title(); ?>
</li>
<?php endwhile; ?>
<li>
<?php echo $first->post_title;?>
</li>
</ul>
</div>
</div>
here is the code, edit it according to your needs:
$(document).ready(function()
{
var imagesrc = $(".example post's image class").attr("src");
$(".the container or post after which you want to put your image").appendTo("<img src='"+imgsrc+"' alt='image' />");
});

Categories