Support » Fixing WordPress » How do I set feature image using the function wp_insert_post

  • Resolved giant slayer


    I am using the function wp_insert_post to automatically add a new post at a specific time each week. How do I assign an image to use as the featured image in conjunction with wp_insert_post?

    Thank you,

Viewing 7 replies - 1 through 7 (of 7 total)
  • Does this look like it will work?

    $new_post_id=wp_insert_post( $my_post );
    $filename='/wp-content/themes/slayer/ipadthumb/' . sprintf("%s", $freebackgrounds->background[$i]->imagefilename);
    $wp_filetype = wp_check_filetype(basename($filename), null );
    $attachment = array(
       'post_mime_type' => $wp_filetype['type'],
       'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
       'post_content' => '',
       'post_status' => 'inherit'
    $attach_id = wp_insert_attachment( $attachment, $filename, 37 );
    wp_publish_post( $new_post_id );

    Does anyone know if an attachment is the same thing as a post_thumbnail or featured image?

    Also is there any way to add an attachment in another directory besides the default

    Currently when I try to use the function wp_insert_attachment, it prepends the wp default media upload directory to the $filename variable.

    So in order for the function to work, the attachment must be in the uploads directory. Is there a way to use the function with images outside of the default(uploads) directory?

    Ok, I guess I am getting closer. I have found an add_attachment hook. But I am not sure how to modify the filename once I get into the hook.

    Any ideas?


    I found another hook called update_attached_file which can change the file location value, but even when using this hook, the _wp_relative_upload_path is prepended to the front. So I still am unable to add an attachment from a folder out side of this default upload folder.

    Anyone with any ideas on how to get around this?

    Unfortunately I was not able to find a work around for attaching files outside of the default uploads folder. And for lack of time, I am going to scrap trying to figure out how.

    However, I did move the files, rewrote some code, and now have a section of code which will post a new post automatically, create an attachment, and set the attachment to be the featured image. The code is as follows.

    [Code moderated as per the Forum Rules. Please use the pastebin]

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘How do I set feature image using the function wp_insert_post’ is closed to new replies.