In WordPress i have a function that correctly save a new processed image as attachment.
What i need is to set as featured image the attachment after its saving.

Here the function:

 /* Save attachment */
        $siteurl = get_option( 'siteurl' );
        $file_info = getimagesize( $newFileName );
        //create an array of attachment data to insert into wp_posts table
        $tableParams = array(
            'post_author' => get_current_user_id(),
            'post_date' => current_time( 'mysql' ),
            'post_date_gmt' => current_time( 'mysql' ),
            'post_title' => $_POST['title'] . '-' . $_POST['filter'],
            'post_status' => 'inherit',
            'comment_status' => 'closed',
            'ping_status' => 'closed',
            'post_name' => sanitize_title_with_dashes( str_replace( "_", "-", $_POST['name'] . '-' . $_POST['filter'] ) ),
            'post_modified' => current_time( 'mysql' ),
            'post_modified_gmt' => current_time( 'mysql' ),
            'post_parent' => 0,
            'post_type' => 'attachment',
            'guid' => $newFileName,
            'post_mime_type' => $file_info['mime'],
            'post_excerpt' => '',
            'post_content' => ''
        );
        // insert the database record
        $attachmentID = wp_insert_attachment( $tableParams, $newFileName, 0 );
        // generate metadata and thumbnails
        if ( $attachmentData = wp_generate_attachment_metadata( $attachmentID, $newFileName ) ) {
            wp_update_attachment_metadata( $attachmentID, $attachmentData );
        }

And i call it in javascript:

    ajaxcall = jQuery.post(ajaxparam.ajax_url,
    {
    action: 'new_image',
    image: imageData,
    format: format,
    title: imageTitle,
    name: imageName,
    filename: largeImage,
    filter: effect,
    nonce: ajaxparam.nonce,
    });

jQuery.when(ajaxcall).done(function(){
editor.insertContent(..............................);
});

So i tried to add to the function:

[......]
if ( $attachmentData = wp_generate_attachment_metadata( $attachmentID, $newFileName ) ) {
wp_update_attachment_metadata( $attachmentID, $attachmentData );
}

global $post;
set_post_thumbnail($post->ID, $attachmentID);

or

add_post_meta($post->ID, '_thumbnail_id', $attachmentID);

or

update_post_meta( $post->ID, '_thumbnail_id', $attachmentID );

in any case without success.
Thanks for any suggestion.

Read more here: Set saved attachment as featured image in WordPress


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: