I use this code for upload image :

function Generate_Featured_Image( $image_url, $post_id  ){
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($image_url);
      $file = $upload_dir['path'] . '/' . $filename;
      $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 );

And this code for manual size :

if(function_exists('add_theme_support')) {
    add_image_size('test', 260, 380, true);

If I upload from wordpress admin, test size make correct

But with my code, test size not make and show original size


I see 2 problems in your last part.

  1. You didn't add hook for the code. Without it, I doubt that the add_image_size function will be executed. I suggest you wrap it in another function and add to after_setup_theme hook with add_action function.
  2. I think the way you use function_exists is unnecessary. With the way you set that conditional block, it will always true because add_theme_support is a built-in core function.

Here is my suggestion code.

if( !function_exists('theme_setup') ) {
    function theme_setup() {
        add_image_size('test', 260, 380, true);
    add_action('after_setup_theme', 'theme_setup');

It's actually quite common way to interact your theme/plugin with WordPress core.

  • I replace your with my code. But not work and now, If upload from wordpress resize not work for me – Mohammad Sep 28 '19 at 12:36
  • Does your site a dev stage? Do you have debug plugins? If no, install them. If yes, please show me the code. There must be a report, log or something can help us understand what's going on inside the code. – Star Light Oct 4 '19 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.