It’s better than running extract()
, which is generally ill-advised, but has the drawback that running ->field()
for each individual meta will run many individual requests to the database. As an alternative, get_post_meta( get_the_ID() )
can be called to get all post meta in a single database query, returned as an array. To transform that into individual variables, something like this can be done:
<?php
foreach( get_post_meta( get_the_ID() ) as $key => $value ) {
if ( '_' === substr( $key, 0, 1 ) ) {
// Private meta prefixed with underscore.
continue;
}
if ( 1 === count( $value ) ) {
// Single value or relationship to a single ID.
${ 'prefix_' . $key } = $value[0];
}else {
// Array; relationship to many IDs.
${ 'prefix_' . $key } = $value;
}
}