get_posts()
and WP_Query
are great for almost everything, but sometimes I want to query all my posts and only display very basic things about them.
For example, if I'm making a page that displays a title and link to every single post on my blog, there's no reason fo开发者_如何学Pythonr me to query the content of those posts. If I have thousands of posts, and the content for each of those posts is huge, then it would be immensely wasteful for me to store all of that content in a php variable just to get the titles and permalinks to those posts. But that's exactly what these two functions do!
I would love to be able to do something like this:
$query = array(
'numberposts' => -1,
'exclude_fields' => 'post_content'
);
$all_posts = get_posts($query);
Is anyone aware of a way to do this without writing a custom query?
(The downside of a custom query -- and it's a huge downside -- is that then you can't use all the great existing functionality of WordPress, e.g., all the loop functions)
The only way I'm aware is to rewrite the SQL query with a filter from a plugin (or functions.php in your theme). Since you only want to remove the content sometimes, you'll have to create a way to register and remove this filter from your template files when necessary.
Here's the filter you'd be hooking on to:
http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_request
Be careful of breaking something by not listing a column WordPress expects, since you'll be replacing a * with an explicit column list.
In general it's probably easier to write the raw SQL and the tiny bit of code you need to get the titles/links/whatever in those few places you need to do so.
You could also ignore all of this, write it with WordPress's built-in functions only, and rely on the fact that you can cache the page and only waste that memory once a day or however often you allow the cache to be refreshed.
精彩评论