Custom code after 3rd, 5th and 7th post in Wordpress - php

Hi there, I have a little bit of a problem. The front page of our new site has a series of thumbnail boxes with rollovers to open certain showcased products. The loop I have written shows all posts currently but will eventually be tied down only to the portfolio category.
My manager however wants a slider with recent blog posts after the third post and a couple of more sliders with references and suchlike after the 5th and 7th posts. I found a little bit of code that injects the same snippet every n posts but this is no good for me because I only want it to happen 3 times and all with different content, including one with a loop inside a loop (where presumably time will move mega slowly haha). Is this possible? If so, can anybody point me towards a code snippet?
Current Loop
<!-- Start of loop -->
<?php if (have_posts()) : ?>
<!-- Start of Post -->
<?php while (have_posts()) : the_post(); ?>
<!-- Check to see if there is featured image -->
<?php if (function_exists('has_post_thumbnail') && has_post_thumbnail()) { ?>
<?php $img_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), array( 960,960 )); ?>
<!-- End Checking -->
<div class="portfolioblock" style="background-image: url('<?php echo $img_src[0]; ?>');">
<a href="<?php the_permalink(); ?>">
<div class="rollover">
<div class="center">
<img src="<?php bloginfo('template_url'); ?>/img/zoom.png" alt="More" />
</div>
<h2><?php the_title(); ?></h2>
<p><?php the_excerpt(); ?></p>
</div>
</a>
</div>
<!-- Start Content Block -->
<?php } else { ?>
<div class="block">
<h2><?php the_title(); ?></h2>
<p><?php the_excerpt(); ?></p>
</div>
<?php } ?>
<!-- End Content Block -->
<?php endwhile; ?>
<!-- End of Post -->
<?php else : ?>
//Something that happens when a post isn’t found.
<?php endif; ?>
<!-- End of Loop -->
And I found this code for injecting a code snippet every n posts.
<?php $postnum++; if($postnum%5 == 0) { ?>
YOUR AD CODE HERE
<?php } ?>

You could count the number of posts that passed and then decide on that:
$postnum++;
if ($postnum == 3 || $postnum == 5 || $postnum == 7) {
echo 'foo';
}

Elaborating on cweiske's answer:
Inserted just before endwhile
<?php $postnum++;
if ($postnum == 4) { ?>
<div class="block"><h2>Blog</h2></div>
<?php }
if ($postnum == 6) { ?>
<div class="block"><h2>References</h2></div>
<?php }
if ($postnum == 9) { ?>
<div class="block"><h2>Meet the team</h2></div>
<?php }; ?>

Basically what you want to do is this.
Before the loop begins, initialise a counter variable to 0.
Each time the loop successfully finds a post, increment the variable.
Now, each loop, you will know how many posts have been displayed.
So at the appropriate place, you check the counter to see if it matches either 3 5 or 7. If it does match, you display the correct block.

Related

HTML only print once in Wordpress Loop

I have a code chunk that is inside the_content(); I'm using acf repeater as well. So when I post a blog, I'll either use the_content(); or the acf field. I have h2 tag ( latest articles ) that I only want printed one time, but it's printing everytime I make a post.
<?php if (have_posts()): while (have_posts()) : the_post(); ?>
<div class="container">
<div class="row">
<div class="col-md-4 sidebar-r">
<?php echo the_content(); ?>
</div><!-- end sidebar-r -->
<?php
$i = $wp_query->post_count;
if($i <=1) {
echo '<h2 class="link-title">
<?php the_sub_field('link_title'); ?>,
</h2>';
}else{
echo '';
}
?>
<div class="col-md-8 links-wrap">
<?php if(have_rows('daily_links')): ?>
<?php while(have_rows('daily_links')): the_row(); ?>
<a href="<?php the_sub_field('link_url'); ?>" target="_blank">
<h2 class="link-title">
<?php the_sub_field('link_title'); ?>,
</h2>
<h3 class="link-source">
<?php the_sub_field('link_source'); ?>
</h3>
</a>
<?php endwhile; ?>
<?php endif; ?>
</div><!-- end links wrap -->
</div><!-- end row -->
</div><!-- end container -->
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>
You'll see I tried using php to count the posts and if more than one post, don't print the tag, but couldn't figure out the exact logic and syntax.
I am honestly struggling a bit to understand exactly what you are trying to do and since I do not even have the posts and other key pieces of information so that I can properly replicate your issue so that I can help you better, this is a little bit challenging. That being said, looking into some ideas I came across another stackoverflow question/answer that might be relevant for you in catching the first post and does something to it. The answer to the referenced question instance was this:
<?php if (have_posts()) : $postCount = 1; while (have_posts()) : $postCount++; ?>
<?php if($postCount == 2) { ?>
// SOMETHING TO DO WITH FIRST POST
<?php } else { ?>
// SOMETHING TO DO WITH ALL OTHER POSTS
<?php } ?>
This was suggested by user Bora in this answer from 2013.
Let me know if that helped!

Blog post layouts wordpress

I'm trying to create a different layout on my blog posts page depending on when the post is created. so blog post 1 will have one class while post two will have another and post 3 will have a final class. hard to explain but here is my code hopefully it will make more sense:
<?php
if(have_posts()):
while(have_posts()): the_post();
$counter = 1;
?>
<?php if($counter == 1){ ?>
<div class="new-row">
<div class="boxes picture-box contact-smaller-box">
<?php the_post_thumbnail(); ?>
</div><!--/.picture box-->
<div class="boxes white-box contact-smaller-box">
<div class="box-inner right-side">
<h2><?php the_title(); ?></h2>
<p><?php echo substr(get_the_excerpt(), 0,70); ?></p>
Read More
</div><!--/.box inner-->
<div class="arrow arrow-left"><img src="..."></div>
</div><!--/.white box-->
</div><!--/.new row-->
<?php $counter = $counter++; ?>
<?php } if($counter == 2){?>
<!-- second section of the blog post content -->
<div class="new-row">
<div class="boxes pink-box contact-smaller-box">
<div class="box-inner">
<h2><?php the_title(); ?></h2>
<p><?php echo substr(get_the_excerpt(), 0,70); ?></p>
Read More
</div><!--/.box inner-->
<div class="arrow arrow-right"><img src="..."></div>
</div><!--/.pink box-->
<div class="boxes picture-box contact-smaller-box">
<img src="..." alt="hearing aids for adults">
</div><!--/.picture box-->
</div><!--/.new row-->
<?php } ?>
<?php
endwhile;
endif;
?>
At the moment both of my test posts are showing as the first type of post, so im thinking my counter is not working correctly, or i have my divs in the wrong position to make this work. im new at working with php so i dont know where i am going wrong. any advice would be brilliant.
After about 4 hours of research and testing different things out i have found a solution (credit):
<?php if (have_posts()) : ?>
<?php $count = 0; ?>
<?php while (have_posts()) : the_post(); ?>
<?php $count++; ?>
<?php if ($count == 1) : ?>
Add your Custom Post Divs Here for the 1st post.
<?php elseif ($count == 2) : ?>
Add your Custom Post Divs Here for the 2nd post.
<?php elseif ($count == 3) : ?>
Add your Custom Post Divs Here for the 3rd post.
<?php elseif ($count == 4) : ?>
Add your Custom Post Divs Here for the 4th post.
<?php else : ?>
Add your Custom Post Divs Here for the rest of the posts.
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
hope it helps someone else out.

How to wrap two posts in ajax-load-more Wordpress plugin?

I am writing blog for Wordpress using Bootstrap grid. My first post is sticky, 100% width of column. Next posts should be placed undearneath it in two columns.
Every two posts are wrapped in div with .row class to keep them in line. I've done this and it worked perfectly.
<div class="col-md-8">
<div class="top-news">
// sticky post
</div>
<div class="next-news-grid">
<?php while ( have_posts() ) : the_post(); ?>
<?php if(is_sticky()) continue; ?>
<?php if( $wp_query->current_post%2 != 0 ) echo "\n".'<div class="row">'."\n"; ?>
<div class="col-md-6 next-news">
<?php if ( has_post_thumbnail() ) { ?>
<?php the_post_thumbnail('next- news-thumbnail'); ?>
<?php } ?>
<h4><?php the_title(); ?></h4>
<hr>
<?php the_content( "read more" ); ?>
</div>
<?php if( $wp_query->current_post%2 != 1 || $wp_query->current_post == $wp_query->post_count-1 ) echo '</div> <!--/.row-->'."\n"; ?>
<?php endwhile; ?>
</div>
</div>
But I want to use ajax-load-more plugin to automatically load posts on the same page after button is clicked. Unfortunately it won't wrap my posts in .row class anymore.
I copied my while loop into repeater template in plugin settings but it seems like it's ignoring the if statement parts with div appending. Therefore it looks ugly when one post is longer and is pushing another to the right AND another down making huge gaps between them.
So how can I wrap every two posts in div.row container with this plugin? Or can I use something else to achieve infinite loading with button?

Show if greater than 3 related articles within same category in wordpress

I seem to be having difficulty.
I need to show a specific piece of text if there are more than or equal to 3 post on a post page template in wordpress. (loop-single.php)
It should be dynamic enough to detect if the total number of post in related category is greater or equal to 3.
here is a code I found which works well on category template pages(archive.php) but it messes up when I use it in a post template.
<?php
$count = 1;
if (have_posts()) : while(have_posts()): the_post(); ?>
<!-- Less than 3 post - nothing shown at all -->
<?php $count++;
endwhile; endif; ?>
<?php if ($count > '3') { ?>
<div> This line shown when 3 or more posts are in current post category</div>
<?php } ?>
NOTE: I'm trying to get this to work on the loop-single.php template file.
Any help would be greatly appreciated,
Thank You
Code updated to include above solution. I fixed a few syntax errors, but its now throwing a T-STRING error: Parse error: syntax error, unexpected T_STRING
here is my full page code:
<?php /* Start loop */ ?>
<?php while (have_posts()) : the_post(); ?>
<?php roots_post_before(); ?>
<article <?php post_class() ?> id="post-<?php the_ID(); ?>">
<?php roots_post_inside_before(); ?>
<header>
<h1 class="entry-title"><?php the_title(); ?></h1>
<!-- POST DATE STAMP -->
<div class="post-top">
<div class="date-stamp">
<b><?php the_time('M d'); ?></b>
</div>
</header>
<div class="entry-content">
<?php the_content(); ?>
</div>
<footer>
<hr />
<?php
$cat = get_query_var('cat');
$posts = get_posts(array('category' => $cat));
if(count($posts) >= 3)
{
<!-- POST FOOTER RELATED CONTENT (2 HORIZONTAL) -->
<h5>Featured: <?php $cats=get_the_category(); echo $cats[0]->cat_name; ?></h5>
<div id="foot-container">
<?php echo do_shortcode("[catlist categorypage=yes comments=yes numberposts=2 class=horizontal-2 offset=2 orderby=date order=desc thumbnail=yes thumbnail_size=75 thumbnail_class=footer-thumb title_tag=p title_class=footer-link comments_tag=p comments_class=comment-count]"); ?>
<div style="clear:both;"></div>
</div>
<hr />
}
else
{
Why hello there LESS than three
}
?>
</footer>
<?php comments_template(); ?>
<?php roots_post_inside_after(); ?>
</article>
<?php roots_post_after(); ?>
<?php endwhile; /* End loop */ ?>
This should get you started:
<?php
$cat = get_query_var('cat');
$posts = get_posts(array('category' => $cat));
if(count($posts) >= 3)
{
//CODE EXECUTED IF THREE OR MORE POSTS EXIST IN CURRENT CATEGORY
}
else
{
//CODE EXECUTED IF LESS THAN THREE POSTS EXIST IN CURRENT CATEGORY
}
?>
EXTRA INFO: The reason why it was failing was because your loop was only performing one iteration. Single posts won't go through the loop more than once because.... well...... it's a single post. What this approach does is take the existing category, and queries all Wordpress posts in the matching category. Using PHP's count function will give you the exact number of posts found with the given parameters.
Word of warning: the script above will not find ALL posts in the matching category. Only the five most recent ones in that given category. If you want an actual total of all matching posts, change one line to the following:
$posts = get_posts(array('category' => $cat, 'numberposts' => -1));
UPDATES TO CODE: This line:
<article <?php post_class(); ?> id="post-<?php the_ID(); ?>"> //missing semicolon after post_class()
And this block:
<?php
$cats=get_the_category();
$posts = get_posts(array('category' => $cats[0]->cat_ID));
if(count($posts) >= 3)
{
?>
<!-- POST FOOTER RELATED CONTENT (2 HORIZONTAL) -->
<h5>Featured: <?php echo $cats[0]->cat_name; ?></h5>
<div id="foot-container">
<?php echo do_shortcode("[catlist categorypage=yes comments=yes numberposts=2 class=horizontal-2 offset=2 orderby=date order=desc thumbnail=yes thumbnail_size=75 thumbnail_class=footer-thumb title_tag=p title_class=footer-link comments_tag=p comments_class=comment-count]"); ?>
<div style="clear:both;"></div>
</div>
<hr />
<?php
}
else
{
echo 'Why hello there LESS than three';
}
?>

Can't get this overly complicated loop to work correctly

So I'm editing the index.php in my WP theme's folder, essentially what I want it to do is this:
Show 4 Posts on first page of blog.
Style the first (newest) post on the first page differently. Style the other 3 the same.
Show 6 Posts on every other paginated page.
Here's the loop I'm working with, the first page appears fine, but for some reason on page 2 and higher it's executing really weird and showing only one post on each additional page. Also, it will only show the title and not the date or excerpt. Here's my code:
<?php
if( is_home() && !is_paged() ){
global $query_string;
parse_str( $query_string, $args );
$args['posts_per_page'] = 4;
query_posts($args);
if (have_posts()) :
while (have_posts()) : the_post();
if (++$counter == 1) { ?>
<div class="featured_post">
<p class="date"><?php the_date('M j, Y'); ?></p>
<h2><?php the_title(); ?></h2>
<?php the_post_thumbnail('featuredblog'); ?>
<?php the_excerpt(); ?>
</div>
<?php } else { ?>
<div class="regular_post">
<p class="date"><?php the_date('M j, Y'); ?></p>
<div class="postimage"><?php the_post_thumbnail('regularblog'); ?></div>
<a href="<?php the_permalink(); ?>"><h3><?php
// short_title($after, $length)
echo short_title('...', 7);
?></h3></a>
<?php the_excerpt(); ?>
</div>
<?php } ?>
<?php endwhile;
else :
// Code for no posts found here
endif;
} else {
global $query_string;
parse_str( $query_string, $args );
$args['posts_per_page'] = 6;
query_posts($args); ?>
<div class="regular_post">
<p class="date"><?php the_date('M j, Y'); ?></p>
<div class="postimage"><?php the_post_thumbnail('regularblog'); ?></div>
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
</div>
<?php } ?>
Maybe there's too many if...else statements in there?
Are you using some kind of framework? that's a pretty bad tempalte engine.
Anyway if yuo need to add style, you should leave the job to CSS.
if you need extremly precision you can just leave a class with a counter for each element you need to style differently.
like <div class="Element<?php echo ++$counter; ?>"></div>
and then you can add your styles in CSS
.Element1,.Element2,.Element3 {styles}
.Element4 {other styles}
in this way you simplify the life with your php code
Keep in mind one day you will not even need to add a class counter.. In the near future you could use the nth-child css selector http://reference.sitepoint.com/css/pseudoclass-nthchild
Edit: damn me I replied someone with 50% AR
my suggestion would follow yes123, but really leave it all to css. basically, all of your posts should be wrapped in a parent div, and each should be classed the same way.
<div id="content">
<div class="post">
<div class="title"></div>
</div>
<div class="post">
<div class="title"></div>
</div>
<div class="post">
<div class="title"></div>
</div>
<div class="post">
<div class="title"></div>
</div>
</div>
that's about what you should resolve to, with more tags in the post, obviously.
from there, the way to style the first post differently would be using the #content > .post:first-child selector.
also, having a different number of posts per page is probably not a good idea. i've actually never really tried it, but i can see where the paging would get screwed up, and you'd probably never see posts 5 or 6. i'm thinking wordpress would probably say that with 6 posts per page, page 2 should always start with post 7. not positive though.
<?php if (is_home() && !is_paged() ) {
global $query_string;
parse_str( $query_string, $args );
$args['posts_per_page'] = 4;
query_posts($args);
} else {
global $query_string;
parse_str( $query_string, $args );
$args['posts_per_page'] = 6;
query_posts($args);
} ?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div class="post<?php echo ++$counter; ?>">
<?php if ( is_home() && !is_paged() && $counter == 1 ) { ?>
do stuff
<?php } else { ?>
do other stuff
<?php } ?>
</div>
<?php endwhile; ?>

Categories