I am new to PHP and WordPress.

I have this scenario.
There are 4 custom fields saved in page, named:

What I need to do now is to fetch their values and save them in an array and save that array back to page as custom field.

I tried following.

$page_list = get_pages();
 foreach($page_list as $page) {
         $post_id = $page->ID;
         $custField1= get_post_meta( $post_id, '_custField1' );
         $custField2= get_post_meta( $post_id, '_custField2' );
         $custField3= get_post_meta( $post_id, '_custField3' );
         $custField4= get_post_meta( $post_id, '_custField4' );

         $custArray[] = array(

         add_post_meta ( $post_id, '_newcust',maybe_serialize($custArray), true );

It does save as array but each custom field is saved as array themself. While I want to achieve the results now as _newcust['_custField1'] , which I can not.

What I am doing wrong here ?

PS: One more thing, above code crashes the website if there are more than 50 pages, how should I optimize it.

Help will be greatly appreciated.

2 Answers 2


This is how I would do it...

$page_list = get_pages();
foreach($page_list as $page) {
     $post_id = $page->ID;

     $custArray = array(
       '_custField1'    => get_post_meta( $post_id, '_custField1', true ),
       '_custField2'    => get_post_meta( $post_id, '_custField2', true ),
       '_custField3'    => get_post_meta( $post_id, '_custField3', true ),
       '_custField4'    => get_post_meta( $post_id, '_custField4', true )

     add_post_meta ( $post_id, '_newcust', $custArray, true );

The value will be serialized by WordPress if it is an array - see https://codex.wordpress.org/Function_Reference/add_post_meta


you should use get_post_meta( $post_id, '_custField1', true );

make $single parameter true so it will return a single value.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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