首页 > 解决方案 > WordPress get_posts() 不返回模板标签

问题描述

我想使用 WordPressget_posts功能获取最新的 5 篇文章。我做了以下事情:

functions.php文件中,我添加了extra.php文件,其中包含以下代码:

if( !function_exists( 'evertstrap_post' ) ) {
function evertstrap_post() {

        $args  = array(
            'post_type' => 'post',
            'numberposts' => 5,
        );

        $recent_posts = get_posts( $args );

        foreach ( $recent_posts as $post ) {
            setup_postdata( $post );
            echo get_the_title();
            echo '<br/>';
        }
        wp_reset_postdata();

    }
}

现在,我从home.php文件调用evertstrap_post()但它没有得到最新的 5 个帖子!

如果我直接将代码放入index.php文件,那么它就可以工作。

我该如何解决?

标签: wordpress

解决方案


我有时在 WordPress 中看到过这种情况echo,输出是不利的。你能试一试吗?

if( !function_exists( 'evertstrap_post' ) ) {
function evertstrap_post() {
        global $post;

        $args  = array(
            'post_type' => 'post',
            'numberposts' => 5,
        );

        $recent_posts = get_posts( $args );

        $output = '';

        foreach ( $recent_posts as $post ) {
            setup_postdata( $post );
            $output .= get_the_title();
            $output .= '<br/>';
        }
        wp_reset_postdata();

        return $output;
    }
}

然后home.php你可以这样做:

<?php echo evertstrap_post(); ?>

推荐阅读