将远程图像导入wordpress,然后设置为自定义字段

时间:2016-06-29 02:56:06

标签: php wordpress

我尝试从远程服务器导入图像并将其设置为自定义字段。 导入和生成附件ID是有效的,但是有些东西会混淆自定义字段。我不知道是否是线程问题。

这是我的代码:

$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();

}

如果我尝试在此自定义字段上设置20个itens,则效果非常好。但是当我需要以250个结果运行这个循环时,它会中断。

我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

我必须将一个非wp数据库迁移到一个wp ready数据库,并且数据库有超过10k的图像。我还设置了导入以便一次完成所有操作(我不仅上传了帖子,还上传了图像和所有元数据,页面等)。

事情是,一次导入内容最有可能超时服务器,并且您只会获得第一个n导入的图像,其余的将因超时或类似错误而无法正常工作。

解决方法是将脚本放在将使用AJAX调用的函数中,并在此时导入一个图像。您只需稍微调整一下即可获取一张图像

我首先检查$imgs数组是否已满 - 来自旧数据库的所有图像都附有所有数据。

如果是,你只需要添加这样的东西

<?php

add_action( 'wp_ajax_import_image', 'import_image_callback' );
add_action( 'wp_ajax_nopriv_import_image', 'import_image_callback' ); // this is only if you're importing from the front end. If in the back end this is not necessary


/**
 * AJAX callback iumport image function
 *
 */
function import_image(){

    $img = $_POST['img'];

    $args = array(
        'post_type'  => 'produto',
        'meta_key'   => 'identifier1',
        'meta_value' => $img
    );
    // The Query
    $image_query = new WP_Query( $args );
    if ( $image_query->have_posts() ) {
        while ( $image_query->have_posts() ) {
            $image_query->the_post();
            update_field('imagens', $img['image_value'], get_the_ID());//You'll need to see what you need from the array value here, I just placed dummy image_value as I don't know what the $img array contains
        }
    }
    /* Restore original Post Data */
    wp_reset_postdata();
}

然后你将使用AJAX调用此函数。现在您可能必须将图像保存为JSON对象和localize it。通过这种方式,您可以在JavaScript中使用该数组来获取当时的图像:

jQuery(document).ready(function($) {
    "use strict";

    var images = localized_object.images_array; //JSON array

    for (var i = 0; i < images.length; i++) {
        var img = images[i]; //something like this - you'll see if this works 100%, but the gist is the same

        upload_image(img); // Call the AJAX callback function
    }


    function upload_image(image){
        $.ajax({
            type: "POST",
            url: localized_object.ajaxurl, //localize this if you're doing this from the from the front end. If you're using it in back end just use ajaxurl.
            data: {
                'action': 'import_image',
                'img': image,
            },
            success: function(response) {
                console.log('Image imported');
            },
            error : function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR + ' :: ' + textStatus + ' :: ' + errorThrown);
            }
        });
    }
});

现在,因为我不知道你的数据库转储是怎么看起来的,所以这不是100%保证可以工作,但是它让你知道如何去做。

希望这会有所帮助:)