How to display sticky post with custom html
-
22-10-2019 - |
Question
I'd like to display 9 posts and be able to insert a sticky post with its custom html template in between 4th & 5th post. Currently the sticky post gets displayed in both the "sticky container" and regular posts.
have_posts()) : $my_query->the_post(); ?>
<?php if ($count <= 9 ){ ;?>
<article>
<?php echo get_the_content(); ?>
</article>
<?php if ($count == 3) {
$sticky = get_option('sticky_posts');
$args = array(
'posts_per_page' => 1,
'post__in' => $sticky,
'ignore_sticky_posts' => 1
);
query_posts($args);
if ( have_posts() ) : while ( have_posts() ) : the_post();
if($sticky[0]) { ?>
<article>
<h1>CUSTOM HTML</h1>
<?php echo get_the_content(); ?>
</article>
<?php
}
endwhile; else:
endif;
wp_reset_query();
}?>
<?php } $count++; ?>
<?php endwhile; ?>
Solution
Your code looks odd to me, typically to insert something between posts you add a counter and count each loop, then add custom code on a particular count, this is for the main loop, for a non main loop or secondary loop us wp_query.
<?php if (have_posts()) : ?>
<?php $count = 0; ?>
<?php query_posts( 'posts_per_page=9' );?>
<?php while (have_posts()) : the_post(); ?>
<?php $count++; ?>
<?php if ($count == 4) : ?>
// Your custom sticky post and html goes here
<?php else : ?>
// the regular loop code goes here such as the below
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
OTHER TIPS
try to exclude the sticky post in the main loop:
global $query_string;
parse_str( $query_string, $args );
$args['post__not_in'] = get_option('sticky_posts');
query_posts( $args );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange