putting in a separator between posts in loop - php

I have the following loop which brings in the title of each post onto my page
html
<?php
if (have_posts()) {
while (have_posts()) {
the_post();
echo '<div class="cell">'.get_the_title().'</div>';
} // end while
} // end if
?>
css
.cell {
display: inline-block;
margin: 0 10px;
}
I want to put a separator between each title/link brought in (not on the ends)
example output
link <div class="separate"></div>
link <div class="separate"></div> link

simple solution using additional flag variable $first
<?php
if ( have_posts() ) {
$first = true;
while ( have_posts() ) {
the_post();
if($first){
$first = false;
} else {
// echo separator
}
echo '<div class="cell">'.get_the_title().'</div>';
} // end while
} // end if
?>

You could put in a <hr> element at the end of your echo like this:
echo '<div class="cell">'.get_the_title().'</div><hr>';

You have to put a counter and compare the counter with posts per page to check if you have reached last post.
You can get posts per page from options table like this:
$default_posts_per_page = get_option( 'posts_per_page' );
Check if you have reached the last post, then don't print out the separator.
$counter = 1;
while ( have_posts() ) {
//your stuffs
if ($counter != $default_posts_per_page) {
//print separator
}
$counter++;
}

Related

Wrapping in while loop is creating extra div

I have this code that's creating an extra empty div when there are extactly 3, 6, 9, etc items.
<?php
$i = 1;
echo '<div class="three-item-wrapper">';
if( have_rows('upcoming_stops_asia') ): while ( have_rows('upcoming_stops_asia') ) : the_row();
?>
<div class="item">Content</div>
<?php
if($i % 3 == 0) {echo '</div><div class="three-item-wrapper">';}
$i++; endif; endwhile; endif;
echo '</div>';
?>
I'm not sure how to fix it.
You are ending the current div and starting a new one when you get to a multiple of 3. If there are no more after that, then the div will of course be empty. One solution would be to accumulate the results and output them in a div only as required:
<?php
if( have_rows('upcoming_stops_asia') ) {
$results = [];
while ( have_rows('upcoming_stops_asia') ) {
the_row();
// Add to the collection of results
$results[] = '<div class="item">Content</div>';
if( count($results) == 3 ) {
// Output three results and reset
echo '<div class="three-item-wrapper">' . implode($results) . '</div>';
$results = [];
}
}
// Output any additional results; no div generated if there aren't any
if( !empty(results) ){
echo '<div class="three-item-wrapper">' . implode($results) . '</div>';
}
}
?>

Is there a way to group Wordpress search results by page template?

On my search results page, I have the standard loop that outputs pages and posts from the search query.
However, I want to create a group or section that gets all of the search results that return is_page_template('template-procedure-minimal') as TRUE first (preferably with a heading), and then output the rest of the list as usual.
How can this be done?
<?php get_search_form(); ?>
<hr class="dotted">
<div id="search-results" class="marginbottom2">
<?php if(have_posts()) {
// Results found
global $wp_query;
echo '<p>'.$wp_query->found_posts.' result'.(($wp_query->found_posts > 1) ? 's' : null).' found.</p>';
while(have_posts()) {
the_post();
echo '<li>'.get_the_title().'</li>';
}
get_template_part('nav', 'below');
} else {
// No results
echo '<p>Sorry, your search returned nothing. Did you spell it correctly?</p>';
} ?>
</div>
<p class="lead halfmargin">Can't find what you're looking for?</p>
<p>Contact Us</p>
You can use get_pate_template_slug() function to determine which template is using.
Here is an example (I haven't tested this code):
`
$page_template_posts = array();
// Results found
global $wp_query;
echo '<p>'.$wp_query->found_posts.' result'.(($wp_query->found_posts > 1) ? 's' : null).' found.</p>';
while(have_posts()) {
the_post();
$post_template = get_page_template_slug(get_the_ID());
array_push($page_template_posts[$post_template], get_post(get_the_ID()));
}
foreach ($page_template_posts as $key => $page_template_post){
echo '<div>'. $key .'</div>';
foreach ($page_template_post as $post_obj) {
echo '<li>'.get_the_title($post_obj->ID).'</li>';
}
}
get_template_part('nav', 'below');
} else {
// No results
echo '<p>Sorry, your search returned nothing. Did you spell it correctly?</p>';
} ?>
`

PHP Html in while loop

I have two html / css content. One of them floating left, the other one floating right.
I wanna pull data from my database, then putting them in a order. Left, right, left, right.
$services = pullservices();
while ($service = mysqli_fetch_object($services)){
for ($i=1; $i<=mysqli_num_rows($services); $i++) {
if ($i % 2 == 0): ?>
Left HTML Content
<?php else: ?>
Right HTML Content
<?php
endif;
}
}
?>
I have 6 items on db. But that code keeps looping one data for 6 times and it doing that for all the data on db.
That is the pullservices function.
function pullservices()
{
global $connect;
$products_query_string = "SELECT
id,
title_tr AS title,
text_tr,
short_text_tr,
image,
icon
FROM services WHERE status = 1 ORDER BY ordering , title_tr";
$products_query_run = mysqli_query($connect, $products_query_string);
return $products_query_run;
You can do this simply by using a flag.
(pseudo code):
$services = pullservices();
$flag=0;
while ($service = mysqli_fetch_object($services)){
if ($flag==0): ?>
Left HTML Content
<?php $flag=1; ?>
<?php else: ?>
Right HTML Content
<?php $flag=0; ?>
<?php
endif;
}
?>
One way you might be able to do this would be to split the data from the recordset and call it later in the html like this
$services = pullservices();
$i=0;
$data=array(
'left' =>array(),
'right' =>array()
);
while( $rs = mysqli_fetch_object( $services ) ){
$key = $i % 2 == 0 ? 'right' : 'left';
/* add the real data rather than placeholder data */
$data[ $key ][]=sprintf('%s HTML Content %d', ucfirst( $key ), $i );
$i++;
}
<div id='left'>
<?php
echo implode( PHP_EOL, $data['left'] );
?>
</div>
<div id='right'>
<?php
echo implode( PHP_EOL, $data['right'] );
?>
</div>

Adding the_post_thumbnail(); via css

I'm trying to set my posts page so that each post item loads with it's featured image as it's background. My code is working properly, but how do I add the post thumbnail as the background for each post? My code is attached below
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* #package Clean Blog
*/
get_header(); ?>
<?php
// Custom loop that adds a clearing class to the first item in each row
$args = array('numberposts' => -1, 'order' => 'ASC' ); //For this example I am setting the arguments to return all posts in reverse chronological order. Odds are this will be a different query for your project
$allposts = get_posts($args);
$numCol = 2; // Set number of columns
// Start Counter
$counter = 0;
foreach ($allposts as $post) {
$content = '<div class="col-md-6 columns-'.$numCol.($counter % $numCol == 0 ? ' first' : '').'">'; // Add class to first column
$content .= '<h3>'.$post->post_title.'</h3>';
$content .= $post->post_content;
$content .= '</div>';
echo $content;
$counter ++;
}
?>
<style type="text/css">
/* Added styles here for the demo, but ideally you would put this in a stylesheet.*/
.columns-2 {
float:left;
}
.first {
clear:both;
margin-left:0;
}
</style>
<!-- /.col-lg-8.col-lg-offset-2.col-md-10.col-md-offset-1 -->
<?php get_footer(); ?>
UPDATE
I've now tried adding it as an inline style, but the raw style is showing up on the page. I feel like I'm missing something easy
http://imgur.com/kkATCAC
<?php
// Custom loop that adds a clearing class to the first item in each row
$args = array('numberposts' => -1, 'order' => 'ASC' ); //For this example I am setting the arguments to return all posts in reverse chronological order. Odds are this will be a different query for your project
$allposts = get_posts($args);
$numCol = 2; // Set number of columns
$thumbnail = get_the_post_thumbnail( $page->ID, 'thumbnail' );
// Start Counter
$counter = 0;
foreach ($allposts as $post) {
$content = '<div class="col-md-6 columns-'.$numCol.($counter % $numCol == 0 ? ' first' : '').'" style="background: url("${thumbnail}") center center/cover no-repeat;">'; // Add class to first column
$content .= '<h3>'.$post->post_title.'</h3>';
$content .= $post->post_content;
$content .= '</div>';
echo $content;
$counter ++;
}
?>
UPDATE 2
I've checked the quotes but now I'm getting a parse error and the page doesn't load at all.
$content = '<div style="background: url('${thumbnail}') center center/cover no-repeat;" class="col-md-6 columns-'.$numCol.($counter % $numCol == 0 ? ' first' : '').'">'; // Add class to first column
You could add it as an inline style:
<?php
$thumbnail = get_the_post_thumbnail( $page->ID, 'thumbnail' );
$content = "<div class='your-post-thing' style='background: url('${thumbnail}') center center/cover no-repeat;'>...stuff...</div>';
echo $content;
?>
OR
Depending on your browser support, you could use object-fit:
<?php
$content .= "<div class='your-post-thing'>";
$content .= "<img class='background-image' src='${thumbnail}' />";
$content .= "</div>";
echo $content;
?>
CSS:
.your-post-thing {
position: relative;
}
.background-image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
$content = '<div style="background-image:url('.wp_get_attachment_url(get_the_post_thumbnail()).')" class="col-md-6 columns-'.$numCol.($counter % $numCol == 0 ? ' first' : '').'">'; // Add class to first column
you can try something like this, and in your css you can add the rules to view correctly the background.

Generate closing divs in WP loop with php

I am new to php and Wordpress and what I am trying to accomplish is listing all my posts by month+year. The month+year is shown as a link, which when clicked, toggles the days. My css code looks like this and is working properly (toggle function done by jquery).
<div class="monat"> <!-- month div -->
Oktober 2014 <!-- Toggle Button -->
<div class="tage"> <!-- toggle div - shown when toggle button clicked -->
12 <!-- day of month -->
20 <!-- day of month -->
22 <!-- day of month -->
23 <!-- day of month -->
</div> <!-- end toggle div -->
</div> <!-- end month div -->
That´s what I have accomplished so far in php. The problem is, that i need 2 closing divs at the end (for class monat and class tage) and I am not sure how to implement them in the php code...
<?php
$prev_month = '';
$prev_year = '';
while(have_posts())
{
the_post();
if(get_the_time('F') != $prev_month || get_the_time('Y') != $prev_year)
{
echo '<div class="monat">'.get_the_time('F Y').'<div class="tage">';
}
?>
<?php the_time('j'); ?>
<?php
$prev_month = get_the_time('F');
$prev_year = get_the_time('Y');
}
?>
Thanks for your help,
Andreas
Thank you so much, hakre!
Works like a charm!
Here is the edited code:
<?php
$prev_month = '';
$prev_year = '';
$divs_opened = false;
query_posts( 'category_name=wurst' );
while(have_posts()) { ## Loop Start
the_post();
$month_changed = (get_the_time('F') != $prev_month) || (get_the_time('Y') != $prev_year);
if ($month_changed) {
if ($divs_opened) {
echo "</div></div>";
}
$divs_opened = true;
{
echo '<div class="monat">'.get_the_time('F Y').'<div class="tage">';
}
}
?>
<?php the_time('j'); ?>
<?php
$prev_month = get_the_time('F');
$prev_year = get_the_time('Y');
} ## Loop End
if ($divs_opened) {
echo "</div></div>";
}
?>
You've already found out how to detect the month change event:
$month_changed = (get_the_time('F') != $prev_month)
|| (get_the_time('Y') != $prev_year);
if ($month_changed) {
...
}
and you output (here I've placed ...) the opening of the divs already. But you're still missing when to place the close of those.
First of all you only need to place closing div tags when you have opened any. You can do this very similar like you do with the months check, just with another variable:
$prev_month = '';
$prev_year = '';
$divs_opened = false; ## third variable
while (have_posts()) {
...
So now when you for the first time open the divs, set that $divs_opened variable to true:
$month_changed = (get_the_time('F') != $prev_month)
|| (get_the_time('Y') != $prev_year);
if ($month_changed) {
$divs_opened = true;
...
}
And as you need to close the divs if they were already opened, you need to check for that, too:
$month_changed = (get_the_time('F') != $prev_month)
|| (get_the_time('Y') != $prev_year);
if ($month_changed) {
if ($divs_opened) {
echo "</div></div>";
}
$divs_opened = true;
...
}
so now this is nearly done, but there is one more place you need to close the divs (if opened), too: that is after the loop:
$prev_month = '';
$prev_year = '';
$divs_opened = false; ## third variable
while (have_posts()) {
...
}
if ($divs_opened) {
echo "</div></div>";
}
That should do it. And I hope it gives you the pointers that you can use a similar method how you detected the month change for the closing divs, too.

Categories