douyingmou1389 2012-07-15 00:38
浏览 5
已采纳

在Wordpress上显示x最近的帖子,包括标题,日期和摘录

I'm looking to find a way to show the last 5 posts on the homepage of my Wordpress website, so i assume i will need to utilise shortcodes to do this, however i cannot find any pre-existing code to add to functions.php that will show the title, date and post excerpt.

Could someone possibly help me with this?

  • 写回答

2条回答 默认 最新

  • duanfangbunao36970 2012-07-15 01:23
    关注

    There are a variety of ways to do this, but the basic idea is similar to the code you'll see in your theme's INDEX.PHP page. You do a query, loop through to show the posts, then reset the query at the end so what you did doesn't interfere with your main page.

    function Last5posts()
    {
        $args = array( "showposts" => 5 );                  
        query_posts($args);
    
        $content = "";
    
        if( have_posts() ) : 
    
            while( have_posts() ) :
    
                the_post();
                $link = get_permalink();
                $title = get_the_title();
                $date = get_the_date();                              
    
                $content .= "<div style='padding: 5px; border: 1px solid red'>";
                $content .= "<h3><a href='$link' target='_top'>$title / $date</a></h3>
    ";
                $content .= "<p class='excerpt'>" . get_the_excerpt() . "</p>";
                $content .= "</div>";
    
            endwhile;
    
            wp_reset_query();
    
        endif;
    
        // Leave one line commented out depending on usage
        echo $content;   // For use as widget
        //return $content; // for use as shortcode
    }
    

    To register this as a widget, enable the "echo" at the end, then add this line to the bottom of your file:

    register_sidebar_widget(__('Last 5 Posts'), 'Last5posts');
    

    You may want to add some extra code to place the output into a widget wrapper DIV like your other sidebar widgets. (Or, not if you use it somewhere besides a traditional sidebar.)

    You could also register this as a shortcode handler using the line below. Comment out the "echo" at the end and uncomment the "return".

    add_shortcode('Last5Posts', 'Last5posts' );         
    

    You'll want to make sure that you don't use the shortcode in blog posts or you might end up calling this recursively. Probably a bad thing.

    You'll probably also want to add a theme-specific prefix to the function name to avoid namespace collisions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作