How to retrieve custom field values and save again as array
-
04-10-2020 - |
Question
I am new to PHP and WordPress.
I have this scenario.
There are 4 custom fields saved in page, named:
_custField1
_custField2
_custField3
_custField4
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(
'_custField1'=>$custField1,
'_custField2'=>$custField2,
'_custField3'=>$custField3,
'_custField4'=>$custField4
);
add_post_meta ( $post_id, '_newcust',maybe_serialize($custArray), true );
}
endforeach;
wp_reset_postdata();
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.
Solution
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
OTHER TIPS
you should use get_post_meta( $post_id, '_custField1', true );
make $single parameter true so it will return a single value.