PHP query stop after count reached - php

I can't seem to figure this out from the php manual. The following code is giving me the 2nd post that is returned. What I would like to do is get 2 posts and then stop.
$count=0;
$related = p2p_type($connected_type)->get_related( get_queried_object_id() );
// Display related posts
if ( $related->have_posts() ) :
$count++;
while ( $related->have_posts() ) : $related->the_post();
if ($count == 2) {
echo the_title();
} else {
echo 'this post won't show up';
}
endwhile;
// Prevent weirdness
wp_reset_postdata();
endif;

you can use if($count >2) break; or break; in the else
break ends execution of the current while .
for more information check this link php manual break

Related

Different size grid with specific order PHP

I need to make a grid similar to this:
Few keywords: specific size pattern, bigger points in higher.
All boxes are custom posts - lets call every box a post.
All different sizes posts have different meta_key called $size:
Yellow/big $size= 1;
Orange/medium $size= 2;
Blue/small $size= 3;
All posts have also meta_key value called $points which are totally different for each (can be anything from 0 to 10000). $points is currently used as orderby.
This is how I call all these posts:
$custom_posts= new WP_Query(array(
'post_type' => 'custom-post',
'meta_key' => 'points',
'orderby' => 'meta_value_num'
));
if ( $custom_posts->have_posts() ) :
echo '<div id="post-items"><ul class="row list-unstyled">';
while ( $custom_posts->have_posts() ) : $custom_posts->the_post();
$size= get_post_meta( $post->ID, 'post_size', true );
$points = get_post_meta( $post->ID, 'post_points', true );
echo '<li>';
if($size == 1) {
?>
//Big yellow box HTML
<?php
}
else if($size == 2) {
?>
//Medium orange box HTML
<?php
}
else if($size == 3) {
?>
//Small blue box HTML
<?php
}
echo '</li>';
endwhile;
echo '</ul></div>';
wp_reset_query();
else :
?>
<p class="text-muted"><?php _e( 'No Posts.', 'aa' ); ?></p>
<?php
endif;
QUESTION:
Any ideas how to query them in specific $size pattern also considering $points (higher points in higher, but do not break the order - LIKE ON MY IMAGE)?
Im working my arse off as we speak (it's 3rd day now on this problem!!) & I would appriciate every idea, comment or source!
What could be useful but I haven't found a working solution yet (I'll add more if I come across some):
Using modulus:
PHP loop: Add a div around every three items syntax
UPDATE 1:
I am not a Wordpress expert by any stretch, so there may be an easier way to do this with a foreach loop, but here it is with a while as you have it in the question:
// This will be used as a counter
$i=0;
while ( $custom_posts->have_posts() ) : $custom_posts->the_post();
// Get size based on counter
switch($i) {
case 0:
case 5:
$size = 1;
break;
case 1:
case 2:
case 3:
case 4:
case 6:
case 7:
$size = 2;
break;
default:
$size = 3;
}
$points = get_post_meta( $post->ID, 'post_points', true );
echo '<li>';
if($size == 1) {
?>
//Big yellow box HTML
<?php
}
else if($size == 2) {
?>
//Medium orange box HTML
<?php
}
else if($size == 3) {
?>
//Small blue box HTML
<?php
}
echo '</li>';
// Increment the counter
$i++;
endwhile;
If I understand your question correctly, this should always display the sizes in the order that you have them (1,2,2,2,2,1,2,2,3,3,3,3,3,3, etc.). Also, if there are less than that number of entries, it will still work, and if there are more, size 3 is the default, so anything else after this will display as 3.

Wrap outputs of a Wordpress query every second item

I think I am pretty close to the solution but I cannot figure out the logic for where I should close the last div.
I have a wordpress query which requests four posts.
I want to wrap every two items in <section class="sponsor-row">
So I have implemented a counter in my query that counts each post, and if it finds two posts have been output it closes the <section> div off.
But I cannot work out how I should work out if the row should be closed again.
Can anyone figure this out? How can I make it wrap every two outputs in <section class="sponsor-row"> ?
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$counter = 0;
echo '<section class="sponsor-row">'; // Opening the section here
if ( has_post_thumbnail() ) {
$counter++;
echo '<div class="grid half">';
echo '<a class="sponsor" href="'.get_the_permalink().'" target="_blank">';
the_post_thumbnail( 'full' );
echo '</a>';
echo '</div>';
if ($counter <= 2){
echo '</section>'; // closing the section if two posts
$counter = 0;
}
}
}
}
Full query here: http://pastebin.com/e6RzZLR5
if you do if ($counter <= 2){ then it will close it each time it is less or equal 2, which means it will close it twice for each item. You should use if ($counter == 2){ and $counter = 0; should be at the top before the query, otherwise you will set it to 0 each loop.
See comparison in php

Php continue not working if not empty?

I am having a loop and that loop has only sticky posts in it. So my logic works like this:
"If Sticky Posts are "EMPTY" break the loop". That code works as expected and looks like this:
<?php //we will get "Sticky Posts" only with this loop and exlude Featured Category
$category = get_cat_ID('Featured');
$col = 1; //Let's create first column
$sticky = get_option( 'sticky_posts' );
$args = array(
/* Add whatever you need here - see http://codex.wordpress.org/Class_Reference/WP_Query */
'paged' => $paged,
'category__not_in' => array($category),
'post__in' => $sticky,
'ignore_sticky_posts' => 1
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query($args);
/*Below is IMPORTANT PART*/
if($wp_query->have_posts()):?><?php while ( $wp_query->have_posts() ) :
$wp_query->the_post();if(empty($sticky))break;?>
<div <?php post_class('col'.$col); ?> id="post-<?php the_ID(); ?>">
<?php if ($col == 1) echo '<div class="row">';//If column 1 create first row ?>
<?php if ($col == 2) echo '<div class="row2">';//If column 2 create second row ?>
<h3 class="mytitle"><?php the_title(); ?></h3>
<div class="entry">
<?php if ( has_post_thumbnail() ):?>
<div class="featured_img">
<?php
the_post_thumbnail();
echo '<div class="featured_caption">' . get_post(get_post_thumbnail_id())->post_excerpt . '</div>';
?>
</div><!--/featured_img-->
<?php endif; ?>
<?php // let's enable more link on pages...
global $more;
$more = 0;
?>
<?php the_content(__('Read more','override')); ?>
<div class="clear"></div>
<div class="custom_fields"><?php the_meta(); ?></div><br/>
<p class="postmetadata">
<?php _e('Filed under:','override'); ?> <?php the_category(', ') ?> <?php _e('by','override'); ?> <?php the_author(); ?><br/><?php the_tags(__('Tags:','override'), ', ', '<br />'); ?>
<?php _e('Posted on: ','override'); ?><?php the_time(get_option('date_format')); ?><br/>
<?php if ( comments_open() ) {
comments_popup_link(__('No Comments »','override'), __('1 Comment »','override'), __('% Comments »','override'));}
else {
_e('Comments are disabled!','override');
}
?>
<?php edit_post_link(__(' Edit','override'), __(' |','override'), ''); ?>
</p>
</div><!--/entry-->
</div><!--/post_class-->
<?php /*Enable Two Column Layout*/
if($col==1) {
$col=2;
echo "</div>";
}
else if($col==2) {
$col=1;
echo "</div>";
}
endwhile; ?>
<?php endif; ?><!--END if THE LOOP (Sticky)-->
<?php
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>
Now before this working code I tried a different logic that goes like this:
"If NOT EMPTY continue the loop" so now everything in my code stays the same except:if($wp_query->have_posts()):?><?php while ( $wp_query->have_posts() ) :
$wp_query->the_post();if(empty($sticky))break;?> so now that code becomes:if($wp_query->have_posts()):?><?php while ( $wp_query->have_posts() ) :
$wp_query->the_post();if(!empty($sticky))continue;?>
Now this is where i got confused because if(!empty($sticky))continue; part does not work as expected because my loop CONTINUES (returns other posts) even if there are no "Stickies". I thought that loop will STOP if there are no stickies but it is not the case. My var_dump($sticky)
shows this if there are sticky postsarray(1) { [0]=> int(214) } and shows this if there are no stickiesarray(0) { }.
My question is: Why the loop continues to return other posts if using if(!empty($sticky))continue; (i thought it will return ONLY "Stickies" if they exist and return NOTHING if they are not here. )
Thank you!!
First off, let me poit out that your logic doesn't quite agree with your code :).
From what I understand from your code, you want to iterate all posts WP_Query() returned, but only render sticky ones. Your if is inside the wile loop, so you have to check if the current post is sticky or not. However, if(empty($sticky)) doesn't do that. It checks if there are any sticky posts at all. A way to check the current post would be if(is_sticky(the_ID())).
Now, concerning continue:
From the php manual:
continue is used within looping structures to skip the rest of the
current loop iteration and continue execution at the condition
evaluation and then the beginning of the next iteration.
So as you can see, continue doesn't stop the loop, but rather attempts to start the next iteration ignoring the rest of the code for the current step. Which is what you want, if the current post is not sticky, in other words if(!is_sticky(the_ID())).
However, I think you don't really need any check at all, since you already specified that you want WP_Query() to fetch only stickies ('post__in' => $sticky).
See also: this WordPress Answers topic.
I don't know well the wordpress code, but in that code, the $sticky variable is never updated in the while loop. So maybe you have to add $sticky = get_option( 'sticky_posts' ); right before the if condition.

Conditional styling for post containers in The Loop

My loop displays posts in two columns using this:
<?php
if (have_posts()): while (have_posts()) : the_post();
$count++;
?>
<?php if ($count == 1) : ?>
<div class="home-ci-row">
<div style="padding: 0px;" class="main-column-item-wrap">
CONTENT OF POST : Title, Thumbnail, Excerpt... etc
</div>
<div class="home-ci-gap"></div><!-- /* the gap */ -->
<?php elseif ($count == 2) : ?>
<div style="padding: 0px;" class="main-column-item-wrap">
CONTENT OF POST : Title, Thumbnail, Excerpt... etc
</div> <!-- main-column-item-wrap -->
</div><!-- /* home-ci-row*/ -->
<?php $count = 0; ?>
<?php else : ?>
// No posts
<?php endif; endwhile; endif; ?>
You can see that the <div class="home-ci-row"> opens in the first count & closes in the second one </div>
so when my loop has an even number of posts works great, but with odd number it doesn't close the div
so My idea is this: If loop has even number
If loop has odd number of posts
By the way, you can do something like:
<?php
$count=0;
while(have_posts()){
if($count%2==0){
echo '<div class="home-ci-row">';
//draw your left div here
}else if($count%2==1){
//draw your gap here
//draw your right div here
echo '</div>';
}
$count++;
}
//close div if count is an odd number
if($count%2==1) echo '</div>';
?>
Is it possible to swap to a for loop? Is this what you need?
for ($i = 0; $i < $numberOfElements; $i++)
{
//if (odd number) && (this is the last element)
if (($i % 0 == 1) && ($i == $numberOfElements - 1))
{
//Special Case
}
else
{
//Normal Case
}
}
Caveat: Watch out for errors, PHP isn't my strongest language
This question was answered on WP Development StackExchange by fischi
Quoting from his answer:
You could do this much easier. As you are making a layout that can be achieved by floats, there is no need to declare a Row every second time.
In my Code example I just youse the $count to determine the Class of the HTML-Element. In combination with the total Number of Posts displayed.
If the total number of posts $wp_query->post_count is reached by the $count AND the total number is odd, I give the Element the Class fullwidth. In the same way, I determine if it is the first or the second (see the IF-Statement).
All I need to do afterwards is output the corresponding Class for each HTML-Element in the Loop. Besides the Class, no Element is diffferent from each other.
I use the Modulo Operator in PHP ( % ) to determine odd/even. It delivers 1 if I use $count % 2 and $count is odd. If you are not sure about this operator, read about it here.
So your code could look like this:
<?php
$count = 0;
if (have_posts()): while (have_posts()) : the_post();
if ( ++$count == $wp_query->post_count && ( $wp_query->post_count % 2 ) == 1 ) {
// if final count is reached AND final count is odd
// full width item
$postclass = "fullwidth";
$opentag = '';
$closingtag = '</div>';
} else if ( ( $count % 2 ) == 1 ) {
// if $count is odd it is the first item in a 'row'
$postclass = "halfwidth first";
$opentag = '<div class="home-ci-row">';
$closingtag = '';
} else {
// second item in a row
$postclass = "halfwidth second";
$opentag = '';
$closingtag = '</div>';
}
?>
<?php echo $opentag; ?>
<div class="main-column-item-wrap <?php echo $postclass; ?>">
CONTENT OF POST : Title, Thumbnail, Excerpt... etc
</div><!-- main-column-item-wrap -->
<?php echo $closingtag; ?>
<?php endwhile; endif; ?>

Wordpress, if function returns "nothing"

I am building a wordpress theme I want to have the next and previous DIV only appear IF their is a next and previous button available.
If there is 10 posts and the display limit is 10 posts I don't want an empty div. However when there are 20 posts and the display limit is 10 I want the next and previous buttons to show in there own div.
I got this far and realized that posts_nav_link() doesn't return null.
function next_previous_div(){
print '<!-- ';
$output = posts_nav_link();
print " -->\n";
if ($output != null)
{
echo '<div class="float post" style="text-align:center">';
echo posts_nav_link();
echo '</div><!-- end post-->';
};
};
There are a few different ways you could test if you'll have a previous/next link:
Test $wp_query->max_num_pages
Get a global reference to the $wp_query object and see if it's greater than 1. If yes, you've got paging links:
global $wp_query;
if($wp_query->max_num_pages > 1){
posts_nav_link();
}
Capture the output of posts_nav_link()
This function echos by default, which is why your null test isn't working. You need to capture the echoed output and then test:
// Capture the echoed output in the $links variable and test on it
ob_start();
posts_nav_link();
$links = ob_get_clean();
if(strlen($links) > 0){
echo $links;
}
I think the closest you will get without custom scripting will be...
if (!empty(get_posts_nav_link()) {
echo '<div class="float post" style="text-align:center">';
echo posts_nav_link();
echo '</div><!-- end post-->';
}

Categories