Ramesh
Ramesh

Reputation: 2403

Filter Only the Blog Posts in Wordpress

I want to display the latest 2 blog posts in my footer. I used while (have_posts()) : the_post(); to display all the blog posts in my blog page ( Almost it's the index page in my case ).

When I tried to filter the latest to blog posts using the same approach I was unable to achieve that.

This is the code so far I have tried. I used a for loop to limit the number of posts.

<ul class="widget-post-list">
     <?php if (have_posts()) : while (have_posts()) : the_post(); for ($i = 0; $i <2; $i ++){ ?>

     <li>
       <h5 class="post-title"><a href="<?php echo get_permalink() ?>"><?php echo wp_trim_words(get_the_title(), 14); ?></a></h5>
     </li>

     <?php } endwhile; else: ?>
       <h5>No Posts found.</h5>
     <?php endif; ?>
</ul>

Through this code I am only returned the Home page link twice.

What is problem here? or is there any other way that I can try?

Upvotes: 1

Views: 77

Answers (1)

charan kumar
charan kumar

Reputation: 2157

Use this in order to display 2 posts, you can change the ul li according to your convenience,

you can use posts_per_page option to filter 2 posts

<ul class="widget-post-list">
// Define our WP Query Parameters
<?php $the_query = new WP_Query( 'posts_per_page=2' ); ?>

// Start our WP Query
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

// Display the Post Title with Hyperlink
<li><h5 class="post-title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h5></li>

// Repeat the process and reset once it hits the limit
<?php 
endwhile;
wp_reset_postdata();
?>
</ul>

Upvotes: 2

Related Questions