• I’m writing a WordPress plugin that displays a lists of all posts organized by month and year. Similar plugins exists, but those all seem to have huge overhead and an outrageous number of queries. I can get all the info I need with one query, but then I run into problems when I’m trying to display the permalink to each post.

    Here is the problem:

    The WordPress function get_permalink($id) accepts $id as either an int or an object. If it’s an object WordPress returns the permalink based on the users chosen structure; however, if it’s an int, it turns the variable into an object first by querying the wp_posts table. This is a problem because if I have hundreds or thousands of posts, then suddenly I have that many queries too!

    Possible solution:

    One obvious solution is, in my original query, to return post_date, post_category, etc. and create the permalink structure myself based on get_option('permalink_structure'), but this doesn’t seem very future proof, and then I’m also rewriting code that already exists within the WordPress core.

    A second solution is to run get_posts() and store the results in an array index by post->ID. Then if I run something like get_permalink($posts[$post_id]) I’m passing an object and it doesn’t require an extra query.

    The problem with this, though, is that querying all posts seems really expensive. A dump of the returned array reveals that all the post’s content is contained in that variable, and that seems completely unnecessary.

    So:

    Is it possible to do a new WP_Query or get_posts and only return certain information — namely, don’t return all that unnecessary content data? If it’s not possible, I think it certainly should be. After all, one of the main criticisms I hear about WordPress is that it’s too slow.

    Also, if anyone has any other suggestions for how I can achieve what I’m trying to do another way, that would be very helpful.

    Thanks!

  • The topic ‘How to return select fields from native WordPress queries’ is closed to new replies.