使用wp_insert_post设置特色图像

时间:2015-01-27 09:05:15

标签: php wordpress wordpress-plugin

            // Auto post ( Unique File Date ).
            $postData = array(
                'post_category' => array( $Category ),
                'post_status' => $Post_Status,
                'post_type' => $Post_Type
            );
            $post_id = wp_insert_post( $postData );

            $getImageFile = 'http://localhost/Multisite/test2/wp-content/uploads/sites/4/Auto Post/twitter.png';

            $attach_id = wp_insert_attachment( $postData, $getImageFile, $post_id );
            require_once( ABSPATH . 'wp-admin/includes/image.php' );

            $attach_data = wp_generate_attachment_metadata( $attach_id, $getImageFile );

            wp_update_attachment_metadata( $attach_id, $attach_data );

            set_post_thumbnail( $post_id, $attach_id );

上面的代码成功发布了帖子,但没有设置帖子特色图片。我不知道我在这里做错了什么。

1 个答案:

答案 0 :(得分:2)

为附件使用不同的$postData

$wp_filetype = wp_check_filetype( $getImageFile, null );

$attachment_data = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => sanitize_file_name( $getImageFile ),
    'post_content' => '',
    'post_status' => 'inherit'
);

$attach_id = wp_insert_attachment( $attachment_data, $getImageFile, $post_id );

目前,您正在将相同的帖子数据传递到帖子及其附件帖子。