Selecting specific posts with an if statement in a counted loop - php

I'm currently counting the posts in the loop...
<?php $count = 0; ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php $count++; ?>
<?php include(locate_template('content.php')); ?>
<?php endwhile; ?>
But need to select specific posts programmatically in an if statement.
The post count I need to select is 1, 4, 5, 8, 9, 12, 13 etc (+3+1r) in sequence.
How can I select these posts (without having to manually type the numbers)?

While technically off topic for WordPress, I think this is something that a good number ueses will enquire about, particularly those that are new to both WordPress and PHP.
As suggested in the comments to your question, you can use a modulus operator to check this, and hopefully this answer will solve your problem.
<?php
$count = 0;
/* Start the Loop */
while ( have_posts() ) : the_post();
$count++;
if($count % 4 === 0 || $count % 4 === 1) :
locate_template('content.php', true);
endif;
endwhile;
?>
As a side note, the locate_template function will automatically load the template file with require_once (if you set the $load parameter), so you don't need to wrap it in include().
I'd recommended that you check if the template exists, and if not fall back on a theme default that will always be there.

Related

Get on every 4th post in WordPress loop

I am currently trying to a create a feature on my category pages where on every 4th preview post, within the category an advert block is display.
essential it will work the following way:
post 1
post 2
post 3
post 4
ADVERT BLOCK
Post 5
Post 6
In my <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
I have the following:
<?php $i = 0; ?>
<?php if (post_num ($i%4 == 0) < (5 - $featured_count)) : echo "this works"; endif ?>
can someone guide me in the right direction
Your more or less there, here's a quick example just showing some arbitrary text or the post title:
<?php
$counter = 0;
if (have_posts()) {
while (have_posts()) {
$counter++;
the_post();
if ($counter % 5 === 0) {
echo 'Advert Here!';
} else {
the_title();
}
}
}
?>
I haven't tested this, but just to give you an idea.
Edit: I should note that since you're looking to insert the advert after the fourth post, $counter % 4 won't do what you think, if you want to show four posts and then the advert, it would be placed in the 5th "position", hence $counter % 5.

PHP while loop not ++'ing variable within if statements

statmentI am currently working on a project. I am having issues with making a variable ++ in the loop while nested in if statements. I really do not understand why it's doing what it's doing. Here is my code.
<?php $i=0;
while ($loop->have_posts() ) : $loop->the_post(); ?>
<?php if(get_field('featured_game') && valid_release(get_field('release_date'))):?>
<div class="item <?php if($i == 0){echo 'active';}?> row carousel-<?=$i;?>">
// do generated html
<style>
.carousel-<?=$i;?>{
// do generated css
}
</style>
</div>
<?php $i++;?>
<?php endif?>
<?php endwhile;?>
</div>
My results have
carousel-
these spots all having returned 0 despite the loop running. meaning that incrment is not happening.
if I remove the if statement the loop works, as expected. The if statement are just to verify criteria to be true. I do can place the ++ outside of the if statement I get the same results.
Could some please explain what I am missing here? This seems like such a basic problem. I really do not understand why $i will not increment when does meet the criteria and posts the correct info. Thanks in advance to anyone who takes the effort.
I ran this code:
<?php $i = 0;
while ($i < 10) : ?>
<?php if (true): ?>
<?php if ($i == 0) {
echo 'active';
} ?>
<?= $i; ?>
<?php $i++; ?>
<?php endif ?>
<?php endwhile; ?>
and the result was:
active 0 1 2 3 4 5 6 7 8 9
so either
get_field('featured_game')
or
valid_release(get_field('release_date'))
must be false.
Try
var_dump(get_field('featured_game'));
var_dump(valid_release(get_field('release_date')));
inside the loop.
Turns out, it was increment properly all along.
My issue turns out to be that bootstraps carousel cycles the the content within the the parent div not the actual div it seems. If I disable it, or look directly at the source, everything is what it is supposed to be.

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.

While cycle create an infinite loop

I wrote this PHP code to put on a wordpress page template:
<?php
query_posts('showposts=10&cat=7');
while (have_posts()) : the_post();
?>
<li class="img-slider">
<?php the_content(); ?>
</li>
<?php endwhile; ?>
When I view the page I don't see any result and the right bar of the browser continue to reduce itself. I have understand that the code create an infinite loop.
Where I mistake?
Thanks
Firstly, you should not use query_posts. It's too invasive for simple loops, and messes with the entire WP_Query. Also showposts should be posts_per_page.
Secondly, it's hard to gauge what this issue is without more context. Perhaps pastebin your entire page, and edit it into your question. My guess is a loop within a loop, and should stop at like a 100 posts. (10 X 10) but if it's reset anywhere else if could very well go infinite!
Use this code instead to create loops:
$custom_query = new WP_Query( 'posts_per_page=10' );
if($custom_query->have_posts()) :
while ( $custom_query->have_posts() ) : $custom_query->the_post();
//global $post; // for stuff like $post->post_name
// Post stuff here
// the_title();
endwhile;
endif;
// Reset Post Data
wp_reset_postdata();
Look at the WordPress codex for more details. http://codex.wordpress.org/Class_Reference/WP_Query#Parameters
You should use an if statement in your loop:
<?php
query_posts('showposts=10&cat=7');
if ( have_posts() ): while ( have_posts() ) : the_post();
?>
<li class="img-slider">
<?php the_content(); ?>
</li>
<?php endwhile; endif; ?>
Without further information, I would say that in each loop of the while statement, the function is returning the first row of the data? So each time the while loop executes you are calling the function again, which is returning the same row over and over again without actually iterating through the result set.

Wordpress postcounter

How do I get a value of how many posts I have? Is there a wordpress tag for that?
I want to use it in my theme like this: Number of posts: 37
Yes there is a function that does that :
$count_posts = wp_count_posts();
From the official Documentation :
The default usage returns a count of the posts that are published. This will be an object, you can var_dump() the contents to debug the output.
Or :
Again qoute :
If you want to show the number of published posts use this code.
$published_posts = wp_count_posts();
echo $published_posts->publish;
I'm not sure which one is the right method, never tried before but seems like both will do the trick.
This code may help you to show no of post in current page
<?php
$count = 1;
if (have_posts()) : while(have_posts()): the_post(); ?>
layout of regular template file here
<?php $count++;
endwhile; endif;
echo $count;
?>
Alternatively you can use as shown in Wordpress Documentation wp_count_posts
<?php
$count_posts = wp_count_posts();
?>

Categories