• I want to make a function that will take an image from the wordpress uploads directory and add it in the media library. So I added the following code in functions.php of my theme. Problem is, that every time I try to post the page keeps loading and never loads! This happens when wp_insert_attachment() is executed. $image_path represents the full local path to the image eg “/var/www/wordpress/wp-content/uploads/2011/06/image.jpg”.

    $wp_filetype = wp_check_filetype(basename($image_path), null );
    $attachment = array(
       'post_mime_type' => $wp_filetype['type'],
       'post_title' => preg_replace('/\.[^.]+$/', '', basename($image_path)),
       'post_content' => '',
       'post_status' => 'inherit'
    );
    $attach_id=wp_insert_attachment($attachment,$image_path);
    // you must first include the image.php file
    // for the function wp_generate_attachment_metadata() to work
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data=wp_generate_attachment_metadata($attach_id,$image_path );
    wp_update_attachment_metadata($attach_id,$attach_data);

    I tried it with the default theme as well. Same problem. Any ideas?

Viewing 1 replies (of 1 total)
  • Thread Starter Gotcher

    (@gotcher)

    I found out that if the above code is executes inside a function called by add_filter it doesn’t work. In any other case it works.

    Eg. this doesn’t work

    add_filter('content_save_pre', 'foobar');
    
    function foobar(){
    $wp_filetype = wp_check_filetype(basename($image_path), null );
    $attachment = array(
       'post_mime_type' => $wp_filetype['type'],
       'post_title' => preg_replace('/\.[^.]+$/', '', basename($image_path)),
       'post_content' => '',
       'post_status' => 'inherit'
    );
    $attach_id=wp_insert_attachment($attachment,$image_path);
    // you must first include the image.php file
    // for the function wp_generate_attachment_metadata() to work
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data=wp_generate_attachment_metadata($attach_id,$image_path );
    wp_update_attachment_metadata($attach_id,$attach_data);
    }

    Any ideas on how could I solve this?

Viewing 1 replies (of 1 total)
  • The topic ‘Problem with wp_insert_attachment!’ is closed to new replies.