1 comment

  1. 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).

Comments are closed.