我想将图像设置为帖子的特色图像。我在 wordpress 文档中找到了这段代码,它将图像保存在上传目录中,但图像不再设置为帖子的特色图像(代码中的 37)。
你能看看吗?非常感谢
<?php
$wp_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' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
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 );
?>
最佳答案
您需要在代码末尾添加以下行:
// add featured image to post
add_post_meta($post_id, '_thumbnail_id', $attach_id);
关于php - 如何在 Wordpress 上使用 php 将图像设置为帖子的特色图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19064919/