Forums

Problem with wp_insert_attachment! (2 posts)

  1. Gotcher
    Member
    Posted 11 months ago #

    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?

  2. Gotcher
    Member
    Posted 11 months ago #

    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?

Reply

You must log in to post.

About this Topic