Skip to content Skip to sidebar Skip to footer

Set-post-thumbnail Wp-ajax Return 0

i try use the media manager from wordpress i use the post editor outside admin wordpress and users can create a posts whit a featured image. I use _wp_post_thumbnail_html function

Solution 1:

This is proper image-uploading code.

<?phpglobal$wpdb;
include ('../../../../wp-load.php');
if ( $_FILES ) {

    if(!function_exists('wp_handle_upload')){
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/media.php');
    }



    $upload_overrides = array('test_form' => false);

    $response = array();
    ini_set('max_execution_time', 0);
    foreach($_FILESas$file){

        $movefile_profile = wp_handle_upload($file, $upload_overrides);
        $filename = $movefile_profile['url'];
        $parent_post_id = $post_id; // please provide post id must$filetype = wp_check_filetype( basename( $filename ), null );
        $wp_upload_dir = wp_upload_dir();
        $attachment = array(
            'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
            'post_mime_type' => $filetype['type'],
            'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
            'post_content'   => '',
            'post_status'    => 'inherit'
        );

        $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
        $filepath = $wp_upload_dir['path'] . '/' . basename( $filename );
        $attach_data = wp_generate_attachment_metadata( $attach_id, $filepath );
        wp_update_attachment_metadata( $attach_id, $attach_data );
        set_post_thumbnail($post_id, $attach_id); // this set_post_thumbnail will set you post thumbnail$response['message'] = 'Done';
    }

    echo json_encode($response);
    die();

}

And for Ajax code, go to this link. If you any problems, then please comment below.

Post a Comment for "Set-post-thumbnail Wp-ajax Return 0"