User meta to post

I think at leasts one approach to this would be the following process:
– get all posts by authors
– foreach post:
– get the author user_meta genere
– update the post_meta with that value

I have not tested any of the code below, so I wouldn’t copy/paste.
But hopefully reading through it will get you in the right direction.

I’ve linked to info on used functions/classes at end.


function update_post_meta_with_user_meta() {
         //setup arguments to only get users with author role
         $user_args = array( 
                          'role' => 'author', 
                          );
        $authors   =  get_users( $user_args );
        //the below foreach could be replaced by adding something like:
        // fields => array( 'ID' ) to $user_args

       //instead I am just going through returned array of WP_User objects 
       //  and putting IDs into array
        foreach ( $authors as $a ) {
            $author_ids[] = $a->ID;
        }

       //setup post query arguments to only give us posts with authors in author_id array
       //which means only posts that have an author with the WP role of author
       // should exclude Editors, Admins, etc. that maybe have authored posts
        $post_args = array(
                          'author__in' => $author_ids,
                        );

        //a new WP_Query with these args   
        $post_query   = new WP_Query( $post_args ) ) );

        //make sure we have posts returned
        if ( $post_query->have_posts() ) {

            //loop
            while ( $post_query->have_posts() ) {

                $post_query->the_post();

                //set $post_id variable to current post
                $post_id = get_the_id();

                //get author meta for author of current post
                $author_genere = get_the_author_meta('genere');

                //update the meta of the current post (by ID) 
                //  with the value of its author's user meta key
                update_post_meta( $post_id, 'genere', $author_genere );
            }

            //reset the postdata
            wp_reset_postdata();
        }

    }
    //hook the above to init
    add_action( 'init', 'update_post_meta_with_user_meta' );

Leave a Comment