使用wp_get_recent_posts

时间:2011-06-15 15:11:58

标签: php wordpress wordpress-theming

我正在编写自己的主题,在侧边栏中,我想列出具有特定标记(“精选”)的三个帖子的详细信息。最初我试过这个:

$args = array(
    'posts_per_page' => 3,
    'tag' => 'featured'); 

$recent_posts = wp_get_recent_posts($args);
foreach( $recent_posts as $post ){
    ...
}

但这不起作用,而是我只有一个帖子,没有标签(在这种情况下是最近的帖子)。

我也尝试使用数字邮件,只是尝试列出带有标签的帖子,指定更多参数,并尝试定位类别而不是标签,其中没有一个对我有用,结果在没有列表之间,只是一个帖子,有时候全部都是。

理想情况下,我希望继续使用wp_get_recent_posts,因为它更简单,绝对是正确的工作功能。因此,我想保留这个问题,具体说明为什么我没有正确使用该函数,而不是使用get_posts或更直接查询的替代解决方案。

5 个答案:

答案 0 :(得分:2)

我有同样的问题,虽然我并没有试图通过标签来限制。这就是我修复它的方法。查看wp_get_recent_posts的实际函数签名(位于/wp-includes/post.php中),至少在我的Wordpress版本中显示:

function wp_get_recent_posts($num = 10)

这当然与Wordpress Codex所说的不同。但是当我用wp_get_recent_posts(5)调用函数时,我实际上得到了最近的5个帖子。

因此,使用此功能看起来不像你想做的那样。

答案 1 :(得分:1)

可能不容易,因为函数引用没有显示任何标记参数: http://codex.wordpress.org/Function_Reference/wp_get_recent_posts

可能需要使用is_tag进一步选择:http://codex.wordpress.org/Function_Reference/is_tag

答案 2 :(得分:1)

在WP 3.9.2中,我有这个功能:

function posts_by_tag($tag, $numberposts = 0) {

    $args = array( 'numberposts' => $numberposts, 'post_status' => 'publish', 'tag' => $tag );
    $recent_posts = wp_get_recent_posts( $args );

    foreach( $recent_posts as $recent ){
            $posts = $posts . '<a href="' . get_permalink($recent["ID"]) . '">'
                    . $recent["post_title"]
                    . get_the_post_thumbnail($recent["ID"], "full")
                    . '</a>';
    }
    return $posts;

}

答案 3 :(得分:0)

好的,因为似乎没有答案,我使用get_posts编写了一个解决方案,其工作方式完全相同。我仍然不知道wp_get_recent_posts我做错了什么。

答案 4 :(得分:0)

是的!您可以在传递给tag的属性中使用带有标记slug的wp_get_recent_posts()参数来过滤该标记。这似乎完全没有记录。例如:

$args = array('tag' => 'my-tag-slug');
$recent_posts = wp_get_recent_posts($args);
相关问题