gpt4 book ai didi

php - 如何从 url 以编程方式设置特色图片?

转载 作者:可可西里 更新时间:2023-11-01 13:41:06 25 4
gpt4 key购买 nike

我有一些帖子 ID,我想从相同的 url 设置这些帖子的精选图片。

这是我添加的邮政编码:

$catid = get_cat_ID("XX Cat");

$my_post = array();
$my_post['post_title'] = $title;
$my_post['post_content'] = $description;
$my_post['post_status'] = 'publish';
$my_post['post_author'] = 1;
$my_post['post_category'] = array( $catid );

$post_id = wp_insert_post( $my_post );

示例:post_id = 1 我想将特色图片设置为:example.com/image.png

我该怎么做?

最佳答案

当图像在您的媒体库中时,您可以将其设置为帖子精选缩略图。要在您的媒体库中添加图片,您需要将其上传到您的服务器。

试试这段代码:

// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$image_name = 'wp-header-logo.png';
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
$filename = basename( $unique_file_name ); // Create image file name

// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}

// Create the image file on the server
file_put_contents( $file, $image_data );

// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );

// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);

// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );

// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');

// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );

// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );

// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

引用网址:http://www.wpexplorer.com/wordpress-featured-image-url/

根据您的要求修改:或该目的忽略 WordPress 标准并将您的所有帖子单个图像上传到您的自定义文件夹并将此图像路径或直接外部图像 url 作为额外属性元字段添加到帖子中,当您将在您的主题上显示帖子时,只需在帮助下使用您的 img帖子编号。演示代码:用于设置图像

<?php
update_post_meta ( 7, 'imgkey', 'www.url.path' );//7 is post id
?>

用于在您要显示的主题页面上获取图像

<?php
$img_value = get_post_meta( get_the_ID(), 'imgkey', true );
?>
<img src="<?php echo $img_value?>">

请注意,如果您是 WordPress 帖子自定义元字段的新手,请阅读这篇文章: https://codex.wordpress.org/Custom_Fields
或者
关于自定义字段的非官方文章:https://premium.wpmudev.org/blog/creating-custom-fields-manually

关于php - 如何从 url 以编程方式设置特色图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com