How to display latest posts Wordpress

拥有回忆 提交于 2019-12-14 03:27:52

问题


On one of my pages I want a section to show the latest 3 news posts.

Is there a simple way of doing this?


回答1:


<?php
function latest_post() {

    $args = array(
        'posts_per_page' => 3, /* how many post you need to display */
        'offset' => 0,
        'orderby' => 'post_date',
        'order' => 'DESC',
        'post_type' => 'post', /* your post type name */
        'post_status' => 'publish'
    );
    $query = new WP_Query($args);
    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post();
            ?>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <?php echo get_the_post_thumbnail('thumbnail'); ?>
            /* here add code what you need to display like above title, image and more */
            <?php
        endwhile;
    endif;
}

add_shortcode('lastest-post', 'latest_post');
?>
  • Add Above code in function.php file.
  • After that paste below shortcode there you want to display latest post.
  • Adin side : [lastest-post]
  • in file : <?php echo do_shortcode('[lastest-post]'); ?>



回答2:


<?php
//Query 3 recent published post in descending order
$args = array( 'numberposts' => '3', 'order' => 'DESC','post_status' => 'publish' );
$recent_posts = wp_get_recent_posts( $args );
//Now lets do something with these posts
foreach( $recent_posts as $recent )
{
    echo 'Post ID: '.$recent["ID"];
    echo 'Post URL: '.get_permalink($recent["ID"]);
    echo 'Post Title: '.$recent["post_title"];
    //Do whatever else you please with this WordPress post
}
?>


来源:https://stackoverflow.com/questions/41631565/how-to-display-latest-posts-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!