How to print wordpress post? - php

As we know, to display posts on wordpress we must use a loop. But in general, the loop used to display posts on wordpress is as follows
$query = new WP_Query( $args );
$query = $query->get_posts();
foreach ($query as $post) :
the_post();
endforeach;
the question is, how do I get $post[$i] so that the results I will get are as follows.
<!-- i want to print wordpress post like this format-->
<div class='grid'>
<div class='column'>
<!-- $i = 0 -->
<!-- start loop -->
<!-- print post -->
<span><?php echo $post[$i]->title; ?></span>
<!-- $i = $i + 3 -->
<!-- end loop -->
</div>
</div>
the concept is I want to display the first post based on the value of $i, then the next post based on the value of $i = $i + 3, so the final result will print $post[0], $post[3], $post[6], [...] , any suggestions?
sorry for my english, Thanks - Edwin.

This should be the solution to display your posts:
<?php
$posts = new WP_Query( $args );
if( $posts->have_posts() ) : //checks if query have posts
while( $posts->have_posts() ) : $posts->the_post();
if( $i % 3 == 0 ) : //every third post ?>
<div class='grid'>
<div class='column-<?php the_ID(); ?>'>
<span>the_title();</span>
</div>
</div>
<?php endif;
$i++;
endwhile;
else :
// if no posts
endif;
wp_reset_postdata();
?>

i got this answer from other question and other forum
$query = new WP_Query( array( 'post_type' => 'page' ) );
$posts = $query->posts;
foreach($posts as $post) {
// Do your stuff, e.g.
// echo $post->post_name;
}
and i make some change from the code to get my result
$query = new WP_Query();
$posts = $query->posts;
$i = 0;
foreach($posts as $post) {
// Do your stuff, e.g.
// echo $post[$i]->post_name;
$i = $i + 3;
}

Related

wrap first post in different div with array_chunk

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');
}
}
}
}

Creating a loop within a loop in Wordpress to display 12 posts in groups of two contained in separate divs

I was hoping one of you Wordpress gurus can help me out here.
I'm trying to create a loop within a loop that presents 12 posts, in 6 rows. In each row you have 2 divs. Each div is meant to display a post title. And the loop runs through all of the 12 posts and groups them correctly - 6 divs, with 2 posts. Each post has it's own unique title.
I've managed to get the loop to breakdown the 12 posts into 6 divs, each with two inner divs in there. But I can't get the inner divs to loop through all the posts. Instead they are just looping through the first two.
So what I end up with is 6 rows, each with two divs. But only the first two posts keep recurring throughout all the rows. What am I doing wrong here?
<!--TESTER -->
<!--TESTER -->
<!--TESTER -->
<div class="section section-testimonials">
<?php
$args=array(
'post_type' => 'testimonial'
);
$query = null;
$query = new WP_Query($args);
if( $query -> have_posts() ) {
echo '';
$i = 0;
while ($query -> have_posts()) : $query->the_post();
if($i % 2 == 0) { ?>
<div class="row">
<?php $loop = new WP_Query( array( 'post_type' => 'testimonial', 'posts_per_page' => 2 ) ); ?>
<?php while ( $loop -> have_posts() ) : $loop -> the_post(); ?>
<!-- Two posts appear here -->
<div class="col-md-6">
<h1><?php the_title(); ?></h1>
</div>
<?php endwhile; ?>
</div>
<?php } ?>
<?php
$i++;
endwhile;
}
wp_reset_query();
?>
</div>
<!--TESTER -->
<!--TESTER -->
<!--TESTER -->
Any help would be incredibly appreciated!
Cheers,
Sanny
Here, I break the problem into pieces, so you can see the loops working on their own.
<?php
$slides = [0,1,2,3,4,5];
foreach($slides as $slide):
?>
<!-- I need to get 6 of these divs which contain 2 cards inside them -->
<div class="item active">
<p>Example Carousel Slide <?php echo $slide;?></p>
</div>
<?php endforeach?>
Then, instead of just echoing a constant <p> tag, you instead put a loop there.
<?php
$posts = ["post1", "post2"];
foreach($posts as $post):?>
<div class="col-md-6">
<?php echo $post;?>
</div>
<?php endforeach?>
I will jump ahead a few steps, but you end up with something like this.
<?php
$posts = [
0=>"post0",
1=>"post1",
2=>"post2",
3=>"post3",
4=>"post4",
5=>"post5",
6=>"post6",
7=>"post7",
8=>"post8",
9=>"post9",
10=>"post10",
11=>"post11"];
for($slideNumber=0; $slideNumber < 6; $slideNumber++):
?>
<!-- I need to get 6 of these divs which contain 2 cards inside them -->
<div class="item active">
<?php
echo("<p>This is slide number " . $slideNumber . "</p>");
for($i=0; $i<2; $i++):?>
<div class="col-md-6">
<?php
$actualPostNumber= ($slideNumber * 2) + $i ;
echo("<p>" . $posts[$actualPostNumber] . "</p>");
?>
</div>
<?php endfor; ?>
</div>
<?php endfor; ?>
Read that code, and try to come up with an expectation for what it will produce. In the end, you should end up with 6 slides, each containing two posts.
The code I posted is a skeleton relative to your eventual solution. However, hopefully this "counters" approach will assist you with assigning the correct number of posts to each carousel slide.
Thanks guys for all the help. I've managed to solve this!!! Here's the solution:
If anyone has any thoughts on making this a better solution lemme know! Cheers
<?php
$args=array(
'post_type' => 'testimonial',
);
$query = new WP_Query($args);
if( $query -> have_posts() ) {
echo '';
$i = 0;
$ids = array();
while ($query -> have_posts()) : $query->the_post();
if($i % 2 == 0) { ?>
<div class="item <?php if($i == 0) :?>active<?php endif; ?>">
<div class="row">
<?php $loop = new WP_Query( array( 'post_type' => 'testimonial', 'posts_per_page' => 2, 'orderby' => 'rand', 'post__not_in' => $ids ) ); ?>
<?php while ( $loop -> have_posts() ) : $loop -> the_post(); ?>
<!-- A single testimonial -->
<div class="col-md-6">
<div class="card card-plain">
<div class="content">
<h4 class="title"><?php the_content(); ?></h4>
<div class="footer">
<div class="author">
<span><?php the_title(); ?></span>
</div>
</div>
</div>
</div>
</div>
<?php $ids[] = get_the_ID(); ?>
<?php endwhile; ?>
</div>
</div>
<?php } ?>
<?php
$i++;
endwhile;
}
wp_reset_query();
?>

custom page taking long to load on wordpress It only show post for today (or latest post)

This custom Page is taking at least 40 seconds to load. The other pages are loading in under 3 seconds. I want to show the post only for today on the front page like a today's news.
What's wrong with the code?
<div class="row">
<?php list($latest_post) = get_posts( array( "posts_per_page"=>1 ));
$date = substr($latest_post->post_date, 0,10); // Show only news from this date
?>
<div class="medium-8 large-8 columns" role="main">
<?php
unset($counter);
/*these are the category ID */
$cats = array(49, 10, 50);
#$cats = get_categories();
foreach($cats AS $cat):
$posts = get_posts( array( "posts_per_page"=>100, "category"=>$cat ));
$catname = get_the_category_by_ID($cat);
$foundPost = false;
foreach($posts AS $post):
$postdate = substr($post->post_date, 0,10);
if($postdate!=$date) break;
if(!$foundPost) { // Print title if at least one post is found
$foundPost = true;
if ( in_category('Category Text') ) {
echo '<div class="redBackground">'.$catname.'</div>';
}
}
?>
<?php
the_post();
?>
<div class="row">
<div class="small-2 columns"><?php the_post_thumbnail();?></div>
<div class="small-10 columns"> <div class="fontSize"><?php the_title(); ?></div>
<div class="contentTag"><?php the_tags(''); ?></div>
<div class="contentText"> <span style="color: #000"><?php echo people_Content(150); ?></span>
</div></div>
</div>
<?php
?>
<?php
endforeach;
endforeach; ?>
</div>
</div>
You need to run a more selective query and only select the posts that are for the day you are on. Below is a query with a loop that should get you where you need to go:
//Get todays date
$today = getdate();
/*these are the category ID */
$cats = array(49, 10, 50);
//setup arguments for query including today's date
$args = array(
'category__in' => $cats,
'date_query' => array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
)
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// this is where you will print out the details of each post
}
} else {
//There were no posts for today.
}
// Restore original Post Data (you may not need this but it can't hurt)
wp_reset_postdata();

Adding a row div after every four post in wordpress

I am trying to add a div class="row" after every four posts in my wordpress website. The following code is used to generate the post types on my page:
<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=8&post_type=branding'.'&paged='.$paged);
while ($wp_query->have_posts()) : $wp_query->the_post();
?>
<div class="col-md-3">
<div class="featured-project-image">
<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail();
}
else { echo'<img src="';
echo get_bloginfo( 'stylesheet_directory' );
echo'/images/placeholder.jpg"/>'; } ?>
</div>
</div>
<?php endwhile;?>
The following should do what you want
<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=8&post_type=branding' . '&paged=' . $paged);
?>
<div class="row">
<?php
$i = 0;
while ($wp_query->have_posts()):
$wp_query->the_post();
if ($i == 4) {
$i = 0;
?>
</div>
<div class="row">
<?php
}
?>
<div class="col-md-3">
<div class="featured-project-image">
<?php
if (has_post_thumbnail()) {
// check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail();
}
else {
echo '<img src="';
echo get_bloginfo('stylesheet_directory');
echo '/images/placeholder.jpg"/>';
} ?>
</div>
</div>
<?php
$i++;
endwhile; ?>
</div>
Starting the div before the while loop ensures the first 4 are also contained in a row.
Create variable, iterate it in each loop step and check if % 4 == 0;:
$i = 0;
while (...) {
echo $i % 4 == 0 ? 'row' : ''; // echo .row in first step too. If you want in the 4th step, just change the result of modulo operator
// your code here
$i++;
}

Exclude a portfolio category from being displayed

I want to ask the Portfolio Page Template to exclude one portfolio category from being displayed in the portfolio. So when it shows the categories: All | Travel | Macro | Archive, etc. I need to exclude Archive (slug archive) from both the top filter and from the All feed, because I want to place that on a separate page called Archive.
How do I do that?
<?php
/*
Template Name: Portfolio number 1
*/
?>
<?php get_header(); ?>
<div class="container">
<div id="homecontent">
<ul id="portfolio-filter" class="filter clearfix">
<li class="active">All</li>
<?php
// Get the taxonomy
$terms = get_terms('categories');
$term_list = '';
// set a count to the amount of categories in our taxonomy
$count = count($terms);
// set a count value to 0
$i=0;
// test if the count has any categories
if ($count > 0) {
// break each of the categories into individual elements
foreach ($terms as $term) {
// increase the count by 1
$i++;
// rewrite the output for each category
$term_list .= '<li>' . $term->name . '</li>';
// if count is equal to i then output blank
if ($count != $i)
{
$term_list .= '';
}
else
{
$term_list .= '';
}
}
// print out each of the categories in our new format
echo $term_list;
}
?>
</ul>
<div style="clear: both;"></div>
<ul id="portfolio-list" class="filterable-grid clearfix centerrow filter-posts">
<?php
// Set the page to be pagination
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
// Query Out Database
$wpbp = new WP_Query(array( 'post_type' => 'myportfoliotype', 'posts_per_page' =>'99', 'paged' => $paged ) );
?>
<?php
// Begin The Loop
if ($wpbp->have_posts()) : while ($wpbp->have_posts()) : $wpbp->the_post();
?>
<?php
// Get The Taxonomy 'Filter' Categories "categories"
$terms = get_the_terms( get_the_ID(), 'categories' );
?>
<?php
$large_image = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'fullsize', false, '' );
$large_image = $large_image[0];
$another_image_1 = get_post_meta($post->ID, 'themnific_image_1_url', true);
$video_input = get_post_meta($post->ID, 'themnific_video_url', true);
$price = get_post_meta($post->ID, 'themnific_item_price', true);
$ribbon = get_post_meta($post->ID, 'themnific_class', true);
?>
<li class="centerfourcol filter" data-id="id-<?php echo $count; ?>" data-type="<?php foreach ($terms as $term) { echo strtolower(preg_replace('/\s+/', '-', $term->slug)). ' '; } ?>">
<?php get_template_part('/includes/folio-types/home_carousel'); ?>
</li>
<?php $count++; // Increase the count by 1 ?>
<?php endwhile; endif; // END the Wordpress Loop ?>
<?php wp_reset_query(); // Reset the Query Loop?>
</ul>
<?php
/*
* Download WP_PageNavi Plugin at: http://wordpress.org/extend/plugins/wp-pagenavi/
* Page Navigation Will Appear If Plugin Installed or Fall Back To Default Pagination
*/
if(function_exists('wp_pagenavi'))
{
wp_pagenavi(array( 'query' => $wpbp ) );
wp_reset_postdata(); // avoid errors further down the page
}
?>
<div style="clear: both;"></div>
</div><!-- #homecontent -->
</div>
<?php get_footer(); ?>
I found the answer, the code below only allows one categorie to be displayed in the portfolio.
‘tax_query’ => array( array( ‘taxonomy’ => ‘categories’, ‘field’ => ‘slug’, ‘terms’ => ‘archive’, ‘operator’ => ‘IN’) ),

Categories