The function get_posts is very useful, and in my opinion under-utilized. It also was incomplete, so I went ahead and completed it.
You can view and use my spanking new functions.php file if you want a complete get_posts.
get_posts is what should be used to get a bunch of posts (or even just one post) outside the wordpress loop (The Loop). It takes 5 arguments :
- numberposts – the number of posts you want returned
- offset – the number of posts you want to skip (like saying skip the first n posts from the results)
- category – the category from which you need these posts
- orderby – order the post by date, or name of any one of the posts table columns
- order – arrange the results in ascending (ASC) or descending (DESC) order
For example,
<?php
$posts =
get_posts('order=ASC&category=4&orderby=name&offset=10&numberposts=6');
foreach ($posts as $post) :
?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
will retrieve posts in category 4 sorted by name in ascending order and give you posts 11 through 16, formatted as specified in the code.
If you are using a nightly of v1.3, here’s the diff.
You can sure put get_links to some innovative and interesting use. The FAQ page uses that to display the 5 most recent answers, for example. Other uses could be to pull up the most recent n posts in each category for display in your “menu”, and so on.
Have fun! Now I get back to C++ programming, to solve what seemed like a small problem a week ago. Small problem indeed! I am firing all my neurons and yet there is no perceivable improvement.
Hi, I´ve a problem using your get_posts. I want to show the title and the content of the last post of a single category. So I pasted this in index.php:
< ?php
$posts =
get_posts('order=ASC&category=3&orderby=name&offset=0&numberposts=1');
foreach ($posts as $post) :
?>
< ?php the_title(); ?>
< ?php the_content(); ?> endforeach; ?>
I added the_content() line expecting to view the last post content, but for my surprise, was the content of my first post, it wasn´t even the right category! Can you help me? Thanks for helping in the support site!
Ok, the text I pasted is not visible (was part in php). To help you figure out, I added the line “the_content();” below “the_title();” and you can view the result in my right bar here: http://www.ladrondeojos.com.ar
My best guess is that you still have the old functions.php file in your wp-includes folder, that does not have all the options that this get_posts I describe has.
So please delete the old functions.php and get the new one.
Carthik, this looks really good…
*hoping hoping*
could a “random” option be placed in the “sort” function, or something, to call up random posts.. i know there are “random posts” plugins out there, but they actually pull up only titles or excerpts.. not the entire article format.. it looks like get_posts would be able to do it.. and it looks like you know how to teach get_posts new tricks. think this is something you’d have time to do?
regardless, thank you for having improved the get_post function in the first place.
Hi, I’ve been trying to get thie to work with my site, but it keeps generating errors with get_post:
i’m not sure what’s going on. i’m basically caopying exactly what you have on this page to test it in mine, but it generates this error instead.
Hi
How can i retrieve the id of individual post that the loop retrieve?
I am using this code:
< ?php $posts = get_posts('order=DSC&category=4&orderby=date&offset=0&numberposts=5');foreach ($posts as $post) :?>
I am sorry, i messed up the layout, here is the code:
< ?php $posts = get_posts('order=DSC&category=4&orderby=date&offset=0&numberposts=5');foreach ($posts as $post) :?>
p endforeach;?>
I too added
< ?php the_content(); ?>following thetitle(); ?>, and got blank spaces, I am sure that I have your updated functions, what should I do?for some reason that didnt come out right, I entered the “the content” tag just after the title tag, and nothin happened but i ams ure i have the updated functions…
Replies have been emailed.
I have to do something about the code not showing up in the comments
Hey Carthik,
< ?php the_content() ?>doesn’t seem to want to work with this code. If I specify a category and number of posts to show, the call for the entry title works fine (title() ?>) but when you call the content it just displays the same contant over and over again.Tags that didn’t show up in the post: [?php the_content() ?], [?php the_title() ?], respectively
I got this to work, as well as any other WP tags, just by adding the simple code:
: start_wpHi, this script looks great, except I can’t get it to work with the POSTMETA tags. Is there any solution?
I don’t understand what exactly you mean by getting it to work with postmeta tags. It may be that the postmeta tags are not returned by the query, but again, I am shooting in the dark here.
I think it was Leaping Lizard who developed a tag called “the_meta_key” which bases itself from “the_meta”. However, this tag can convert any custom field you have and be used individually, and very flexibly unlike the “the_meta” tag. A sample tag looks like this:
< ?php the_meta_key("yourcustomkey"); ?>If you’d like to give it a try, just add this code to your page in the header:
he_meta_key( $tag='') {global $id, $post_meta_cache;
$inUL = false;
if ($keys = get_post_custom_keys()) {
foreach ($keys as $key) {
if ($key == $tag || $tag=='') {
$values = array_map('trim',$post_meta_cache[$id][$key]);
$value = implode($values,', ');
if (!$inUL) { echo ""; $inUL = true; }
echo "$value";
}
}
if ($inUL) { echo ""; }
}
}
And create some custom keys for yourself and place the Tag anywhere in the loop, however you want the tag to be used
Thanks for the reply!
Crap, the first line of the function code should look like this:
f/unct/ion th/e_met/a_k/ey( $/ta/g=”) /{
(without and slashes!)
The tag looks like this:
(without any slashes)
Very sorry here!
I’ll try this again… (but add the normal PHP parts to this tag:
the_meta_key(“yourcustomkeyname”);
Hey,
Using WP 1.3. Replaced the present functions.php with the one you’ve modified. Now I’m seeing this result:
Parse error: parse error, unexpected T_STRING in /this/is/not/the/path/htdocs/wp-includes/functions.php on line 4
I don’t need to use 1.3 in order to use it, do I?
Little help? Thanks.
Crap…typo…should say: “Using WP 1.2.”
I have posted a diff for 1.3 and the file itself for 1.2 in the post. Use one of these, depending on your version.
yeah. brain is on hold today. saw that post too. I’m using 1.2 and am seeing that T_STRING parse error…just straight replacement? I’ll try grabbing it with IE instead of Safari…
Hi Carthik! I’m using a 1.3 build (I probably shouldn’t be). Can I still just replace my functions.php file with yours?
BTW, any idea why the wiki says you can do get_posts(‘category=1′) when you obviously can’t? They want me to bang my head on the wall?
Err, I guess I should say “what’s a DIFF?” (This is why I shouldn’t be using nightlies, but too bad.)
Ruby, a Diff is a file that shows the difference between the old file and the new file (just shows what needs to be added, is all)
So you can read the diff file, and find the old lines in the old file, and add the new lines to the file to make it work the suggested way. Should be a simple enough matter, I hope.
Please note that you may have to add the statement start_wp(); just like in the default “loop” for posts in index.php to get everything displayed just fine within the loop that displays the posts you got using get_posts.
You could have edited the wiki, but I’ll look into it
Wow, you’re up too?
Actually I guessed this was the case and did what you said, and it works great now. I didn’t use start_wp() either.
As always, thanks for your patience and your great ideas!
You’re Welcome
I also found it useful to add a “postid” param to allow fetching of single posts:
if (isset($r['postid'])) {
$posts = $wpdb->get_results("SELECT DISTINCT * FROM $tableposts WHERE id = " . $r['postid'] );
} else {
$posts = $wpdb->get_results("SELECT DISTINCT * FROM $tableposts LEFT JOIN $tablepost2cat ON ($
tableposts.ID = $tablepost2cat.post_id) WHERE category_id = ". $r['category'] . " AND post_date < = '$now' AND
(post_status = 'publish') GROUP BY $tableposts.ID ORDER BY " .$r['orderby']. " ".$r['order']." LIMIT " . $r['o
ffset'] . ',' . $r['numberposts']);
}
Good stuff. I had gone ahead and made “category=” work, and then came across this. I added a couple of lines to make the default orderby and order work better:
if (!isset($r['orderby'])) $r['orderby'] = 'date';
if (isset($r['orderby'])) $r['orderby'] = "post_".$r['orderby'];
if (!isset($r['order'])) $r['order'] = 'DESC';
I’m building a web site for my university student newspaper and your code has been a life saver. Thank you for showing a newbie how to interact with wordpress. The site should be live within the next couple of days so check it out and see what you think.
This is sort of like what I am trying to do, but not exactly. I would like to have 5 icons at teh top of my page for the “Last 5 categotys” posted, just like http://www.slashdot.org does. Do any of you know how to do this? I am a php noob but I really appreciate any help.
Carthik, any chance of turning this into a plugin? It seems like it would be fairly straightforward. Also, do you have any idea how difficult it would be to add a “Post Order” field, that would let you organise posts manually?