简体   繁体   English

如何从 url 以编程方式设置特色图像?

[英]How to set featured image programmatically from url?

I have some post id's and I want to set these posts' featured images from same url.我有一些帖子 ID,我想从相同的 url 设置这些帖子的特色图片。

Here is my adding post codes:这是我添加的邮政编码:

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

Example: post_id = 1 I want to set featured image to: example.com/image.png示例:post_id = 1 我想将特色图片设置为:example.com/image.png

How can I do this?我怎样才能做到这一点?

You can set an image as post featured thumbnail when it is in your media library.您可以将位于媒体库中的图像设置为发布精选缩略图。 To add an image in your media library you need to upload it to your server.要在您的媒体库中添加图像,您需要将其上传到您的服务器。

try this code :试试这个代码:

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

ref url : http://www.wpexplorer.com/wordpress-featured-image-url/参考网址: http : //www.wpexplorer.com/wordpress-featured-image-url/

Modified as your requirement : for that purpose ignore wordpress standard and upload your all post single image on your custom folder and add this image path or direct external image url into post as extra attribute meta field and when you will show post on your theme then just use your img with help of post id.根据您的要求进行修改:为此,请忽略 wordpress 标准,将所有帖子的单个图片上传到您的自定义文件夹中,并将此图片路径或直接外部图片网址添加到帖子中作为额外的属性元字段,当您将在您的主题上显示帖子时,只需在帖子 ID 的帮助下使用您的 img。 demo code: for setting image演示代码:用于设置图像

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

for getting image on your theme page where you want to show it用于在您要显示的主题页面上获取图像

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

Note if you are new in wordpress post custom meta fields then read this article https://codex.wordpress.org/Custom_Fields请注意,如果您是 wordpress 发布自定义元字段的新手,请阅读本文https://codex.wordpress.org/Custom_Fields
or或者
unofficial article about custom fields : https://premium.wpmudev.org/blog/creating-custom-fields-manually关于自定义字段的非官方文章: https : //premium.wpmudev.org/blog/creating-custom-fields-manually

if you have to load an image and then assign as thumbnail of the post, the quicker way is to use media_sideload_image and then set_post_thumbnail如果您必须加载图像然后指定为帖子的缩略图,则更快的方法是使用 media_sideload_image 然后使用 set_post_thumbnail

https://developer.wordpress.org/reference/functions/media_sideload_image/ https://developer.wordpress.org/reference/functions/media_sideload_image/

$url     = "http://url-of-the-image.jpg";
$post_id = [post id]
$desc    = "image description";

$image = media_sideload_image( $url, $post_id, $desc,'id' );

set_post_thumbnail( $post_id, $image );

I used wordpress' media manager wp.media to upload featured images from a form in my plugin.我使用 wordpress 的媒体管理器 wp.media 从插件中的表单上传特色图片。 It has it's own advantages and it's pretty simple.它有它自己的优点,而且非常简单。

Wordpress 媒体管理器

HTML part: In the html form you only need 2 elements, a button and a hidden input field to store the image ID and send with the form. HTML 部分:在 html 表单中,您只需要 2 个元素、一个按钮和一个隐藏的输入字段来存储图像 ID 并与表单一起发送。 (You can use ajax to update but in my case, this method was simpler) (您可以使用 ajax 进行更新,但在我的情况下,此方法更简单)

 <input type="button" name="select-thumbnail" class="button" Value="Select Thumbnail"> <input type="hidden" name="thumbnail-id" value="">

Javascript (jQuery): On the javascript, you need to- Javascript (jQuery):在 javascript 上,您需要-

  1. open the media manager on button click单击按钮打开媒体管理器
  2. insert the id into hidden input when an image is selected选择图像时将 id 插入隐藏输入

 jQuery('input[name="select-thumbnail"]').click(function(e) { e.preventDefault(); var thumbMediaManager; //open if already initialized if(thumbMediaManager) { thumbMediaManager.open(); return; } //create media manafer thumbMediaManager = wp.media({ title: 'Select Thumbnail', multiple: false, library : { type : 'image', } }); //when an image is selected thumbMediaManager.on('select', function() { var selection = thumbMediaManager.state().get('selection').first().toJSON(); //console.log(selection); //insert the id into input field jQuery('input[name="thumbnail-id"]').val(selection.id); //Finally, open the media manager thumbMediaManager.open(); });

Php: When the form is submitted, retreive the image attachment ID, and get the post id (from wp_insert_post in my case), and use set_post_thumbnail() Php:提交表单时,检索图像附件ID,并获取帖子ID(在我的情况下来自wp_insert_post),并使用set_post_thumbnail()

$thumbnail_attachment_id = sanitize_text_field($_POST['thumbnail-id']);
$postId = wp_insert_post($newPost);

set_post_thumbnail($postId, $thumbnail_attachment_id);

set_post_thumbnail: https://developer.wordpress.org/reference/functions/set_post_thumbnail/ set_post_thumbnail: https : //developer.wordpress.org/reference/functions/set_post_thumbnail/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM