programing

wp_insert_post를 사용하여 특징 이미지 설정

minimums 2023. 10. 30. 20:51
반응형

wp_insert_post를 사용하여 특징 이미지 설정

// 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 );

위의 코드는 성공적으로 게시물을 만들었으나 게시물 특징 이미지를 설정하고 있지 않습니다.제가 여기서 뭘 잘못하고 있는지 모르겠습니다.

다르게사용$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 );

현재 동일한 게시물 데이터를 게시물과 첨부 게시물로 전달하고 있습니다.

나는 그 기능을 사용합니다.wp_upload_bits이미지 업로드가 용이한 새로운 워드프레스 기능입니다.내 코드의 두번째 줄에$post당신의$post_idid와 업로드 파일 디렉토리의 경우 나는 사용자 정의 폴더를 만듭니다.custom-uploads당신의 이해를 돕기 위해 또는 당신은 내 4번째 코딩에서 그것을 없앨 수 있습니다.'./'. 'custom-uploads' . '/'

$upload = wp_upload_bits($_FILES["file"]["name"], null, file_get_contents($_FILES["file"]["tmp_name"]));

$post_id = $posts; //set post id to which you need to set post thumbnail
$filename = $upload['file'];
$uploadfile = $uploaddir['basedir'] . '/'. 'custom-uploads' . '/';

move_uploaded_file($filename, $uploadfile);  // (file name , designation)

$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => sanitize_file_name($filename),
    'post_content' => '',
    'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $posts );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );

wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );  // set post thumnail (featured image) for the given post

언급URL : https://stackoverflow.com/questions/28166651/set-featured-image-using-wp-insert-post

반응형