0

This question already has an answer here:

I have several custom post types. For some i need to query them based on a single meta field, but for others i have a dozen individual meta fields. If i create an array and convert it into JSON, will it be faster if i call 12 meta fields one by one or call the JSON, parse it and then have the variables?

A quicker alternative i was thinking would be to save all of the meta fields one by one, but then also create a JSON version of them all. In cases where i need to query by meta i can do it and when displaying a list i dont neet to perform 12 queries * num posts.

marked as duplicate by Pieter Goosen, Mayeenul Islam, bueltge, Tom J Nowell Jul 1 '16 at 14:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Just a note, storing data as an array is almost never a good idea with sorting and searching in mind – Pieter Goosen Jun 16 '16 at 14:21
  • also, WordPress already serializes php data structures, no need for json. – Milo Jun 16 '16 at 15:46
  • You shouldn't serialise database fields, especially if you want to do queries on them. Of note if you PHP serialise instead there are security risks involved that could trigger object creation and code execution on deserialisation – Tom J Nowell Jul 1 '16 at 14:26
1

If i create an array and convert it into JSON, will it be faster if i call 12 meta fields one by one or call the JSON, parse it and then have the variables?

Virtually no difference. The meta API means that all meta keys/fields/values are pulled into memory from the database at most once per post. So this:

$keys = [ 'this', 'that', 'then' ];
$data = [];
foreach ( $keys as $key )
    $data[ $key ] = get_post_meta( $post->ID, $key, true );

...will be just as efficient as:

$json = get_post_meta( $post->ID, 'json', true );
$data = json_decode( $json );

...well, slightly optimized (reduce the get_post_meta overhead - by which I mean PHP processing, WordPress filters etc. not database queries):

$meta = get_post_meta( $post->ID ); // No key, all metadata returned
$data = [];
foreach ( $keys as $key ) {
    $data[ $key ] = isset( $meta[ $key ] ) ? maybe_unserialize( $meta[ $key ][0] ) : null;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.