JSFiddle - React, Tailwind, and code Playground
HTML
Code: <code>let url = getPostMeta( 19, 'large_preview', true )</code>:
<pre id="out1"><b>url:</b> </pre>
Code: <code>let ms = getPostMeta( 19, 'many_values', false )</code>: <i>or</i><br>
Code: <code>let ms = getPostMeta( 19, 'many_values' )</code>:
<pre id="out2"><b>ms[0]:</b> </pre>
Code: <code>let ma = getPostMeta( 19 )</code>
<pre><b>ma.large_preview:</b> <span id="out3"></span><br><b>ma.many_values[0]:</b> <span id="out4"></span></pre>
<hr>
<b>After we merged <code>posts</code> with <code>postsMeta</code></b>, <code>JSON.stringify( posts[0].meta )</code> is:
<pre id="out5"></pre>
And <code>posts[0].post_parent</code> is:
<pre id="out6"></pre>
<hr>
Thanks for visiting and see Stack Overflow <<a href="https://stackoverflow.com/a/50081721/9217760">https://stackoverflow.com/a/50081721/9217760</a>> for more details.
— <small><a href="https://stackoverflow.com/users/9217760/sally-cj">Sally</a></small>
CSS
/* Demo styles. */
pre {
max-width: 768px;
margin-left: 1em;
padding: 10px 15px;
background: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
color: #333;
white-space: pre-wrap;
}
code {
padding: 2px 4px;
background: #f9f2f4;
border-radius: 4px;
color: #c7254e;
font-size: 0.75em;
}
JavaScript
// `single` has no effect if `meta_key` is empty.
function getPostMeta( post_id, meta_key, single ) {
let id = String( post_id ),
pm = [];
postsMeta.map( m => {
let a = ( ! meta_key ) ||
( meta_key === m.meta_key );
if ( a && id === m.post_id ) {
pm.push( m );
}
});
let meta = {},
mk = {};
pm.map( m => {
let k = m.meta_key, v;
if ( undefined === meta[ k ] ) {
meta[ k ] = m.meta_value;
} else {
v = meta[ k ];
if ( undefined === mk[ k ] ) {
meta[ k ] = [ v ];
mk[ k ] = 1;
}
meta[ k ].push( m.meta_value );
m[ k ]++;
}
});
pm = null;
mk = meta_key ? mk[ meta_key ] : null;
if ( mk ) {
return single ?
meta[ meta_key ][0] : // Returns a single meta value.
meta[ meta_key ]; // Returns all the meta values.
}
return meta_key ?
meta[ meta_key ] : // Returns the value of the `meta_key`.
meta; // Or returns all the post's meta data.
}
const posts = [{"ID":"19","post_author":"2","post_date":"2010-12-31 23:02:04","post_date_gmt":"2010-12-31 23:02:04","post_content":"Harry Potter was not available for the first sitting of the Halloween Picture. I hope everyone had a safe and fun Halloween. Tomorrow is picture retake day, please send back your previous prints if you want retakes. It is also hot lunch. See You tomorrow!","post_title":"Happy Halloween","post_excerpt":"","post_status":"publish","comment_status":"open","ping_status":"open","post_password":"","post_name":"happy-halloween","to_ping":"","pinged":"","post_modified":"2011-01-03 05:26:11","post_modified_gmt":"2011-01-03 05:26:11","post_content_filtered":"","post_parent":"0","guid":"http:\/\/localhost\/mrskitson.ca_wordpress\/?p=19","menu_order":"0","post_type":"post","post_mime_type":"","comment_count":"1"}];
const postsMeta =...