WordPress在上传后生成图像大小

时间:2019-09-28 作者:Mohammad

我使用此代码上载图像:

function Generate_Featured_Image( $image_url, $post_id  ){
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
    if(wp_mkdir_p($upload_dir[\'path\']))
      $file = $upload_dir[\'path\'] . \'/\' . $filename;
    else
      $file = $upload_dir[\'basedir\'] . \'/\' . $filename;
    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        \'post_mime_type\' => $wp_filetype[\'type\'],
        \'post_title\' => sanitize_file_name($filename),
        \'post_content\' => \'\',
        \'post_status\' => \'inherit\'
    );
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

    require_once(ABSPATH . \'wp-admin/includes/media.php\');
    require_once(ABSPATH . \'wp-admin/includes/file.php\');
    require_once(ABSPATH . \'wp-admin/includes/image.php\');

    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    $res1 = wp_update_attachment_metadata( $attach_id, $attach_data );
    $res2 = set_post_thumbnail( $post_id, $attach_id );
}
手动尺寸代码:

if(function_exists(\'add_theme_support\')) {
    add_theme_support(\'post-thumbnails\');
    add_image_size(\'test\', 260, 380, true);
}
如果我从wordpress管理员上传,test 大小使正确

但是用我的代码,test 尺寸不制作并显示原始尺寸

1 个回复
SO网友:Star Light

我在你的最后一部分看到了两个问题。

您没有为代码添加挂钩。没有它,我怀疑add_image_size 将执行函数。我建议您将其包装在另一个函数中并添加到after_setup_theme 钩住add_action 功能function_exists 是不必要的。通过设置条件块的方式,它将始终为真,因为add\\u theme\\u支持是一个内置的核心函数这是我的建议代码。

if( !function_exists(\'theme_setup\') ) {
    function theme_setup() {
        add_theme_support(\'post-thumbnails\');
        add_image_size(\'test\', 260, 380, true);
    }
    add_action(\'after_setup_theme\', \'theme_setup\');
}
实际上,用WordPress核心与主题/插件交互是很常见的方式。