I have a problem with showing sticky posts in a custom loop. This is the code I’m using to for the custom loop:
<?php
$post_from_cat_a = new WP_Query(array(
'category_name' => 'events', //Get posts from category a
'posts_per_page'=> 2 //Limit it to the latest one
));
if( $post_from_cat_a->have_posts() ){
while( $post_from_cat_a->have_posts() ): $post_from_cat_a->the_post(); //Display output here for post from category a
$category = get_the_category();
if($category[0]){
echo '<div class="cat-events"><a href="'.get_category_link($category[0]->term_id ).'">'.$category[0]->cat_name.'</a></div>';
}
get_template_part( 'content', 'events' );
endwhile;
}
?>
I can’t figure it out why it doesn’t work.
Later edit: this is my entire homepage.php where the problem occurs and this is the content-events.php file used for each post in the events category.
Second edit: If I include 'post__in' => get_option('sticky_posts')
in the wp_query
array the sticky post is shown but it doesn’t list the next post in the category. Only the sticky posts appears on the page, it’s kind of ignoring the 'posts_per_page'=> 2
argument.
Does anyone have any idea why this is happening?
if you use
'post__in' => get_option('sticky_posts')
then you are only filtering on posts that are sticky.As mrwweb said you need to look at your query. Then think of the ‘loop’ you want.
Do you want to show all posts in a specific query or all posts that are sticky in all categories?
You might need to do 2 queries or a customer database query to select the posts you want.
You are better off adding a tag or custom meta data to a post as you can’t create a loop for sticky posts in a specific category.
Some background
You’re trying to use
query_posts
ANDWP_Query
at the same time. You only use one at a time and they’re used in different ways. You’ll need to review the WP_Query and query_posts pages on the Codex and then also read these two WPSE threads:Now, you’ll see that on the WP_Query page that sticky posts are enabled by default, so this really should cause you any problems. The
query_posts
line you have is straight off the Codex and with this description:Fixing issue
Your WP_Query stuff looks ok, so I suspect the problem is somewhere in your loop or with the content itself.
var_dump()
ofget_option( 'sticky_posts' )
and confirm that the ID of the page you want is there.'ignore_sticky_posts' => 0
to yourWP_Query
$args.content-home.php
. It’s possible that you’re outputting a different loop on that page.