开发者

Using wp_get_recent_posts

I am writing my own theme, and in the sidebar I want to list details on three posts with a specific tag ('featured'). Initially I tried this:

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

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

But that didn't work, instead I got only a single post, that didn't have the tag (the most recent post in this case).

I have also tried it with using numberposts, just trying to list posts with the tag, specifying more parameters, and tr开发者_如何学编程ying to target categories rather than tags, none of which has worked for me, results ranging between getting no listing, just the one post, and sometimes all of them.

Ideally I'd like to stay using wp_get_recent_posts as it is a lot simpler and is definitely the right function for the job. As a result I'd like to keep this question specific to why I'm failing to use the function properly, rather than alternative solutions using get_posts or querying more directly.


I had the same problem, although I wasn't trying to limit by tag. Here's how I fixed it. Looking at the actual function signature for wp_get_recent_posts (which is in /wp-includes/post.php), at least in my version of Wordpress, shows:

function wp_get_recent_posts($num = 10)

This is, of course, different from what the Wordpress Codex says. But when I called the function with wp_get_recent_posts(5), I actually got the 5 most recent posts.

So it doesn't look like what you wanted to do is possible with this function.


Might not be easy, as the function reference doesn't show any tag parameters: http://codex.wordpress.org/Function_Reference/wp_get_recent_posts

Might have to further select with is_tag: http://codex.wordpress.org/Function_Reference/is_tag


In WP 3.9.2 i have this working function:

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;

}


Ok, since there doesn't seem to be an answer, I wrote a solution using get_posts that works in exactly the same way. I still don't know what I was doing wrong with wp_get_recent_posts though.


Yes! You can use a tag parameter with a tag slug in the attributes passed to wp_get_recent_posts() to filter on that tag. This seems to be entirely undocumented. Example:

$args = array('tag' => 'my-tag-slug');
$recent_posts = wp_get_recent_posts($args);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜