Skip to content

Instantly share code, notes, and snippets.

@isotrope
Created February 6, 2015 17:34
Show Gist options
  • Save isotrope/173b94941aff2240303e to your computer and use it in GitHub Desktop.
Save isotrope/173b94941aff2240303e to your computer and use it in GitHub Desktop.
Getting all our Meta Ducks in a row.
<?php
/**
* Build an array object out of basic WP_POST info as well as the meta_keys we want
*
* @param WP_POST $post_object
* @param string|array $expected_meta_keys
*
* @return array
*/
public static function prep_my_wp_object( WP_POST $post_object, $expected_meta_keys ) {
$post_id = $post_object->ID;
// Let's set up some of the properties found in a WP_POST
$post_info = array(
'ID' => $post_id, // Do YOU remember when it's ALL CAPS?
'id' => $post_id, // Do YOU remember when it's all lowercase?
'post_title' => $post_object->post_title,
'post_content' => $post_object->post_content,
'post_date' => $post_object->post_date,
);
// Get all of the Metas!
$all_meta = get_post_meta( $post_id );
// Let's keep it a bit dump and let the user send an array or a string of $meta_keys
$all_meta_keys = is_array( $expected_meta_keys ) ? $all_meta_keys = $expected_meta_keys : $all_meta_keys[] = $expected_meta_keys;
// Looping through all the expected fields
foreach ( $all_meta_keys as $meta_key ) {
if ( ! empty( $all_meta[ $meta_key ] ) && ! empty( $all_meta[ $meta_key ][0] ) ) {
$post_info[ $meta_key ] = maybe_unserialize( $all_meta[ $meta_key ][0] );
} else {
$post_info[ $meta_key ] = false;
}
}
return $post_info;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment