如何在WordPress上用php将图片设置为帖子特色图片?

xsuvu9jc  于 2022-10-30  发布在  PHP
关注(0)|答案(3)|浏览(153)

我想设置一个图片作为一个职位的特色图像。我发现这段代码在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 );
?>
wfypjpf4

wfypjpf41#

您需要在代码末尾添加以下行:

// add featured image to post
add_post_meta($post_id, '_thumbnail_id', $attach_id);
a7qyws3x

a7qyws3x2#

正如我所理解的,你想使用一个图像作为一个精选的图像在后权利?那么为什么你不使用后端精选的图像浏览选项在后。从那里你可以简单地uplod图像作为精选和精选的图像,你可以显示与此代码在您的页面the_post_thumbnail( $size, $attr );

fwzugrvs

fwzugrvs3#

您可以使用以下功能:

// Set featured image
set_post_thumbnail( $post_id, $image_id );

相关问题