I have a custom loop with this args:
$sticky = count(get_option('sticky_posts'));
$main_loop = array (
'posts_per_page' => 4 - $sticky
);
I want to do the following:
But i won't get it to work. At the moment i have the following situation:
In short: When i stick posts from the latest 3 posts it is not working and when i stick more than 3 posts it is not working.
This is the full loop:
<section>
<h2>Aktuelles</h2>
<?php
$sticky = count(get_option('sticky_posts'));
// WP_Query arguments
$main_loop = array (
'posts_per_page' => 4 - $sticky
);
// The Query
$query = new WP_Query( $main_loop );
// The Loop
while ( $query->have_posts() ) : $query->the_post(); ?>
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
<?php endwhile; wp_reset_postdata(); ?>
</section>
Since I found no answer to this question I used another approach with 2 loops combined that always show 4 posts. The trick is to substract the sticky post count from the second loop.
<?php
$sticky = count(get_option('sticky_posts'));
if ($sticky > 0) {
?>
<?php
// First loop with sticky posts
$main_loop_s = array (
'posts_per_page' => $sticky,
'post__in' => get_option('sticky_posts'),
);
// The Query
$do_not_duplicate = array();
$query = new WP_Query( $main_loop_s );
// The Loop
while ( $query->have_posts() ) : $query->the_post(); $do_not_duplicate[] = $post->ID; ?>
<h3><?php the_title(); ?></h3>
<?php endwhile;
?>
<?php // stickycheck end
}
?>
<?php
$sticky = count(get_option('sticky_posts'));
if ($sticky < 4) {
?>
<?php
$allstickys = 4 - $sticky;
// Second loop with rest of posts up to 4
$main_loop_ns = array (
'posts_per_page' => $allstickys,
'offset' => $sticky,
'post__not_in' => $do_not_duplicate
);
// The Query
$query = new WP_Query( $main_loop_ns );
// The Loop
while ( $query->have_posts() ) : $query->the_post(); ?>
<h3><?php the_title(); ?></h3>
<?php endwhile; wp_reset_postdata();
?>
<?php // stickycheck end
}
?>