logo

Import Images with All Import and Metabox.io

Import Images with All Import and Metabox.io

Ετικέτες: importmetabox

In Sociality we have used Metabox.io to create metaboxes for our WordPress Websites and we all use WP All Import to import massive data. Unfortunately when it comes to images there is no way  to import the images directly into custom fields of Metabox. But don’t worry we came up with a workaround.

1. We import all images need to the gallery massively

2. We map in the csv or xml we are going to import the filenames of the images we imported. We call this IMAGE_NAME_FIELD in our example

3. While we import the data we find by using the filename the appropriate attachment id and assign it to our actual metabox image field. We call this ACTUAL_IMAGE_FIELD in our example.

We can use the following code in our functions.php or in our site specific plugin in order to make this work

//Import Data
function data_autoprocess( $post_id ) {
    if(get_post_type($post_id)=='OUR POST TYPE'){

        $image = wp_get_attachment_by_post_name(get_post_meta( $post_id,'IMAGE_NAME_FIELD',true));
        if(!empty($image)){
            update_post_meta( $post_id, 'ACTUAL_IMAGE_FIELD',$image->ID );
        }
    }
}
add_action( 'pmxi_saved_post', 'data_autoprocess', 10, 1 );

//Asset function to find image by name
if( ! ( function_exists( 'wp_get_attachment_by_post_name' ) ) ) {
    function wp_get_attachment_by_post_name( $post_name ) {
        $args           = array(
            'posts_per_page' => 1,
            'post_type'      => 'attachment',
            'name'           => trim( $post_name ),
        );

        $get_attachment = new WP_Query( $args );

        if ( ! $get_attachment || ! isset( $get_attachment->posts, $get_attachment->posts[0] ) ) {
            return false;
        }

        return $get_attachment->posts[0];
    }
}
2 found this helpful