[resolved] Optimized related posts snippet (taxonomy based) (3 posts)

  1. Ahrengot
    Posted 2 years ago #

    Optimized related posts
    I used to use this snippet to fetch related posts:


    It looks up all terms in a given taxonomy associated with the current post. If it finds any, it’ll loop over them and, for each term, execute a new database query looking after other posts sharing that taxonomy term.

    My version
    Last week, I worked on a website that was doing too many DB queries, forcing me to go through the code and optimize where possible.

    I noticed the snippet above was to blame for a lot of those queries and decided to rewrite a less database-intensive version. This is what I came up with:

    The main difference is that instead of looping over each taxonomy term and firing off a new query, I simply do a new WP_Query with the tax_query param (Line 22). This results in only a single database query, and saved me about 60 queries per page.

    My question is: do you see anything wrong with my snippet? From what I can tell it does exactly the same thing.

    If not, I'd like to post an article on my blog explaining why this is a better approach, and maybe trawl the web a bit trying to help people learning about the tax query thing, because I'm seeing the first snippet, the one with a query for each loop iteration, almost everywhere people ask for a related posts snippet.

  2. keesiemeijer
    Posted 2 years ago #

    My question is: do you see anything wrong with my snippet? From what I can tell it does exactly the same thing.

    No, not really, looks good.

    You could further optimize it by getting the term IDs directly with wp_get_post_terms();

    $term_ids = wp_get_post_terms($post->ID , $taxonomy, array("fields" => "ids"));

    In other situations where you would only need one field from an Array or Object you can use: wp_list_pluck()

    Personally I would just return the posts from the get_posts() function instead of looping through them with a new WP_Query and then return them. get_posts() and new WP_Query use the same arguments/parameters

  3. Ahrengot
    Posted 2 years ago #

    Thanks a lot. Very helpful reply.

Topic Closed

This topic has been closed to new replies.

About this Topic