1

I'm using the plugin WP All Import to import a special post type. The plugin includes an action hook pmxi_gallery_image that runs after the import that saves the attachment images to the post gallery.

I've included this action in a function in my function.php file in my child theme:

//After WP All Import runs this will place the attached photos in the gallery images field by post id
add_action('pmxi_gallery_image', 'update_images_meta', 10, 3);
function update_images_meta( $pid, $attid, $image_filepath ) {

// Get all the image attachments for the post
$param = array(
        'post_parent'       => $pid, 
        'post_type'         => 'attachment', 
        'post_mime_type'    => 'image'
);

$attachments = get_children( $param );

// Initialize the array
$atts = array();

// Fill the array with attachment ID's
foreach($attachments as $attachment) {
        $atts[] = $attachment->ID;
}

// Disable this hook which was overwrinting our changes
// remove_action( 'save_post', 'flexible_save_details', 10 );

// Update the post's meta field with the attachment arrays
update_post_meta( $pid, 'images', $atts );
}

This outputs an array of the image post id's:

a:4:{i:0;i:38985;i:1;i:38986;i:2;i:38987;i:3;i:38983;}

I need to include a string length before id, with the id's encapsulated in quotes, so the output looks like this for the gallery the theme uses:

a:4:{i:0;s:4:"7613";i:1;s:4:"7615";i:2;s:4:"7616";i:3;s:4:"7618";}
1
  • 1
    update_post_meta() when saving an array will run wp_maybe_serialize() which should automatically add the string count. If you're looking at the value in the database and it's not doing this, something is possibly wrong with your WordPress install.
    – Howdy_McGee
    Jun 18, 2015 at 16:48

1 Answer 1

1

Your data is being serialize properly. Your code saves an array of integers. Integers are not strings and so a string length is not saved. Run the following code and it should illustrate the point:

$str = 'a:4:{i:0;s:4:"7613";i:1;s:4:"7615";i:2;s:4:"7616";i:3;s:4:"7618";}';
$str = maybe_unserialize($str);
var_dump($str);
echo '<br/>';
var_dump(maybe_serialize($str));
echo '<br/>';
$str = array(
  1234,4567,8910,1112
);
var_dump(maybe_serialize($str));
echo '<br/>';
$str = array(
  '1234','4567','8910','1112'
);
var_dump(maybe_serialize($str));

To get the results you want, save strings and not integers:

// Fill the array with attachment ID's
foreach($attachments as $attachment) {
        $atts[] = "$attachment->ID";
}
0

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.