设置缩略图后 WP-AJAX 返回 0


set-post-thumbnail wp-ajax return 0

我尝试使用WordPress的媒体管理器,我在管理员WordPress之外使用帖子编辑器,用户可以创建带有特色图像的帖子。我使用_wp_post_thumbnail_html功能来显示图像或显示上传文件的链接,所有用户都可以上传图像并上传作品,但无法显示特色图像或分配给帖子。

在WP-AJAX上,白色操作:设置后缩略图返回0,图像未分配给新帖子。WP-AJAX.php:

JSON:真 thumbnail_id:3952 _wpnonce:B02E8553F1 操作:设置缩略图后

响应: 0

我的代码为:

<?php $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
                        //$postid =  get_post( $post_id );
                        echo _wp_post_thumbnail_html( $thumbnail_id, $post_id );
                    ?>
                    <br>

非常简单,从wordpres显示媒体管理器,允许上传特色图像,但不允许分配给新帖子。 有什么解决方案吗?

编辑

:在编辑帖子中工作正常,我想是因为特色图像需要帖子ID,但是在WordPress的新帖子中允许上传图像并将其分配给新帖子。

这是正确的图像上传代码。

<?php
global $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($_FILES as $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();
}

对于 Ajax 代码,请转到此链接。如果您有任何问题,请在下面发表评论。