Tharindu Thisarasinghe
Tharindu Thisarasinghe

Reputation: 3998

Save custom meta-box all the fields data at once

I have a custom meta-box on new-post page which allows user to add photos continuously. He can add more and more (Any number of photos).

So, I have a problem when saving this data. Because, the number of fields is not same.

My code is as follows:

if( isset( $_POST[ 'photo-title-1' ] ) ) {

    $photos = array(
        0 => array($_POST[ 'photo-title-0' ], $_POST[ 'photo-url-0' ], $_POST[ 'photo-desc-0' ]),
        1 => array($_POST[ 'photo-title-1' ], $_POST[ 'photo-url-1' ], $_POST[ 'photo-desc-1' ]),
        2 => array($_POST[ 'photo-title-2' ], $_POST[ 'photo-url-2' ], $_POST[ 'photo-desc-2' ])
        ............................................
        ............................................
        ............................................
         n => array($_POST[ 'photo-title-n' ], $_POST[ 'photo-url-n' ], $_POST[ 'photo-desc-n' ])

    );

    $serialized_array = serialize($photos);
    update_post_meta( $post_id, 'photos', sanitize_text_field($serialized_array) );

}

As you can see, there can be n number of fields and what's the way of saving all of them at once?

Upvotes: 1

Views: 556

Answers (1)

ElChiniNet
ElChiniNet

Reputation: 2902

You could iterate with a while in the POST array:

$sum = 0;

while( isset($_POST['photo-title-' . $sum]) ){

    $photos[] = array(

        $_POST[ 'photo-title-' . $sum ],
        $_POST[ 'photo-url-' . $sum ],
        $_POST[ 'photo-desc-' . $sum ]

    );

    $sum++;

}

$serialized_array = serialize($photos);
update_post_meta( $post_id, 'photos', sanitize_text_field($serialized_array) );

EDIT

Following the comments, the POST Array could not contain all the fields, there is an update to solve this:

$reg = '/^photo\-(title|url|desc)\-(\d+)$/';

$filter = preg_grep($reg, array_keys($_POST));

$photos = array();

foreach($filter as $param){

    $index = preg_replace($reg, '$2', $param);

    if( !isset($photos[$index]) ) $photos[$index] = array();

    $photos[$index][$param] = $_POST[$param];

}

$serialized_array = serialize($photos);
update_post_meta( $post_id, 'photos', sanitize_text_field($serialized_array) );

If you want consecutive indexes in the Array, you can add:

$photos = array_values($photos);

Upvotes: 1

Related Questions