Custom Fields
Re-Envisioned
Support General Feature Suggestion: one query to get all custom fields in a group

  • Creator
    Topic
  • #15363
    Resolved Mauro
    Participant

    With wp_instert_post we can create and add meta data to the post at the same time.
    Is there a get_post (or even better get_posts) counterpart that will allow us to grab posts with meta fields without the need of using get_post_meta for each custom field?
    Given how metabox defines its custom fields, it should be possible to create a function that will get all fields at once by referencing the field group. I am currently doing something like this but I end up calling the metabox get meta wrapper function in a foreach cycle.
    It would be ideal to make a join and grab a post with all its meta, querying the DB only once.
    Has this been considered?
    Is this already available?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Author
    Replies
  • #15376
    Anh Tran
    Keymaster

    Hi Mauro,

    If performance is your concern, then using Meta Box helper functions or get_post_meta is totally fine. WordPress will query all post meta only once, cache them and don’t make extra queries if you call get_post_meta multiple times.

    In case you want a single function that returns all meta value, WordPress has get_post_custom() function:

    https://codex.wordpress.org/Function_Reference/get_post_custom

    Just a note that it returns the raw values stored in the post meta, the same as get_post_meta.

    #17021
    Mauro
    Participant

    This is good news, but it still means you need to call it and hit the DB for each post rather then doing one DB query to get the posts and the meta you need together in one object.

    #17064
    Anh Tran
    Keymaster

    Hi Mauro,

    If you make a query with WP_Query, then by default, WP will automatically fetch meta data for all posts in the query. So, whenever you call get_post_meta (or rwmb_meta, or get_post_custom, e.g. any meta-related functions), there will be no extra queries to the DB made.

    See the update_post_meta_cache for the WP_Query. Better explanation can be found here: https://10up.github.io/Engineering-Best-Practices/php/

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.