2

I need to be able to export the data within WordPress so that each object is contained in a single row, like a flat table.

Imagine each post type as it's own database table, containing columns that represent all of the metadata.

Right now, I'm having the hardest time trying extract all of the key / value pair metadata.

I've tried get_posts and then looping over each post and extracting the metadata with get_post_meta ... but this just produces a bunch of convoluted array data.

What would be the recommended way of doing this?

0
3

Problem is that meta values are not unique key/value data.

E.g. with the key 'OneKey' you can have a lot of values for the same post.

So, in a flat table, for the column 'OneKey' you should have multiple rows where the post id is the same and seems to me is not what you want.

Sure, you can take ony one value treating all meta key as singular, but also a single meta value can contain an array of data... in that case you should save that array as serialized.

Finally note that WP has some hidden meta fields that use for internal scope, e.g. '_edit_lock' or '_edit_last' and others..., probably you'll want to skip those.

$posts = get_posts('nopaging=1');
$flatten = array();
$blacklist = array('_edit_lock', '_edit_last', '_wp_old_slug');
if ( ! empty($posts) ) { foreach ( $posts as $post ) {
  $metas = get_post_custom( $post->ID );
  $keys = array_keys($metas);
  if ( ! empty($keys) ) { foreach ( $keys as $_key ) {
     if ( in_array($_key, $blacklist) ) continue;
     // the first value for every meta key
    $post->$_key = maybe_serialize($metas[$_key][0]);
  } } 
  $flatten[$post->ID] = $post;
} }

// for debug
echo '<pre>';
print_r( $flatten );
echo( '</pre>');

$flatten will be a one-dimensional array of objects (WP_POST class instances).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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