I am trying to get the latest posts on my blog. These are being displayed in a little widget in my front page on my website. I am getting a little trouble though. The posts are getting multiplied. http://goo.gl/Q2STSC, Here is my SQL query.
$posts = DB::connection('blog')->select("
SELECT a.post_title AS title, a.post_name AS slug, meta_value AS thumbnail,a.post_content AS contenido, a.post_date AS fecha
FROM wp_postmeta, wp_posts AS a
JOIN wp_posts AS b ON a.ID = b.post_parent
WHERE b.ID = wp_postmeta.post_id
AND meta_key = '_wp_attached_file' AND a.post_status = 'publish'
ORDER BY fecha
LIMIT 0 , 6");
Try this
<?php $args = array(
'posts_per_page' => 6,
'offset' => 0,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
$posts_array = get_posts( $args );
foreach ( $posts_arrayas $post ) : setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach;?>
Please use above code to fetch latest post from you blog.In above code you can see different parameters
posts_per_page : Number of post to get
offset : Starting Post number likeyou do in custom query limit 0[offset],6[posts_per_page]
order : Orderby [ DESC / ASC]
orderby : date [ column on which order clause has to perform]
post_type : post ( type of post] ( if you want to get posts for custom posts like news, then you can pass news as post_type
post_status : publish ( status of post )
Also in foreach you can permalink [ link of the post ] and the_title( title of the post)
For more details you can check here https://codex.wordpress.org/Function_Reference/get_posts