Fetch posts from category in custom page template

I have created custom template (Sell items) for pages. I want to display posts from specific category on page using that custom template. That is working perfectly but only if there are at least one post in the category. If there is nothing it will give following error.

What might be wrong?

Notice: Undefined offset: 0 in /home/usernamethis/public_html/5423565/wp-includes/class-wp-query.php on line 3152

Here is the code. Html ripped out for better reading:

<?php
/*
Template Name: Sell items
Template Post Type: post
*/
get_header(); 
global $post;
?>

<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>

<!-- THIS IS WHERE PAGE CONTENT IS DISPLAYED -->
<?php the_content(); ?>
<!-- THIS IS WHERE PAGE CONTENT IS DISPLAYED -->

<?php
$args = array( 'numberposts' => 20, 'category_name' => 'sell-items' );                      
$posts = get_posts( $args );                        
?>

<?php if(!empty($posts) && count($posts)>0) : ?>

<?php
foreach( $posts as $post ): 
setup_postdata($post);?> 
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php 
endforeach; 
wp_reset_postdata();
?>
<?php endif; ?>
<?php endwhile; ?>

<?php else: ?>

Not found
<?php endif; ?>

Read more here: Fetch posts from category in custom page template

Leave a Reply

Your email address will not be published. Required fields are marked *