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条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?