1

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; ?>
2

You can use WP_Query instead the get_posts() function:

  $args = array( 'numberposts' => 20, 'category_name' => 'sell-items' );  
  $wp_query = new WP_Query($args);

if ($wp_query->have_posts()) : while($wp_query->have_posts()) : $wp_query->the_post();

echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
    endwhile;
  endif;
0

It looks like your endif and endwhile are misplaced. Try this:

<?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 endif; ?>
<?php endwhile; ?>

<?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 else: ?>

Not found
<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.