mardi 28 juin 2016

Import remote image to wordpress, then set to custom field

I'm trying to import images from a remote server and set it to custom fields. Importing and generating a attachment id is working, but something is messing with the custom fields. I don't know if is a thread issue or something.

Here's my code:

$sql = 'SELECT * FROM produto';
$retval = mysql_query( $sql, $connection) ;

while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{

    $file = $row['imagem'];
    $filename = basename($file);
    $upload_file = wp_upload_bits($filename, null, file_get_contents($file));
    if (!$upload_file['error']) {
        $wp_filetype = wp_check_filetype($filename, null );
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_parent' => $parent_post_id,
            'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );

        $imgs[$row['modelo']][]['imagem'] = $attachment_id;

        if (!is_wp_error($attachment_id)) {
            require_once(ABSPATH . "wp-admin" . '/includes/image.php');
            $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
            wp_update_attachment_metadata( $attachment_id,  $attachment_data );

        }
    }

}

foreach ($imgs as $key => $value) {

    $args = array(
    'post_type' => 'produto',
    'meta_key'   => 'identifier1',
    'meta_value' => $key);
    // The Query
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            update_field('imagens', $value, get_the_ID());
        }
    }
    /* Restore original Post Data */
    wp_reset_postdata();

}

If I try to set 20 itens on this custom field, it works perfectly. But when I need to run this loop with 250 results, it breaks.

What am I doing wrong?

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire