使用 wp_insert_post 插入 wordpress post 并附上特色图片

Insert wordpress post using wp_insert_post and attach the featured image

我尝试在 functions.php 文件中使用 wp_insert_post 函数插入一个 post,post 成功插入,但不是特色图片的附件。

任何人都可以提供帮助,我下面的代码有什么问题:

$post_if = $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title like '$title'");
if($post_if < 1){
    //coded
    $new_post = array(
        'post_title' => $title,
        'post_content' => $contents,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type' => 'post'
);

$post_id = wp_insert_post($new_post); 
$image = "https://fake.org/image.jpg";


$media = media_sideload_image($image, $post_id); //$post_id from wp_insert_post


// therefore we must find it so we can set it as featured ID
if(!empty($media) && !is_wp_error($media)){
    $args = array(
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'post_status' => 'any',
        'post_parent' => $post_id
    );

    // reference new image to set as featured
    $attachments = get_posts($args);

    if(isset($attachments) && is_array($attachments)){
        foreach($attachments as $attachment){
            // grab source of full size images (so no 300x150 nonsense in path)
            $image = wp_get_attachment_image_src($attachment->ID, 'full');
            // determine if in the $media image we created, the string of the URL exists
            if(strpos($media, $image[0]) !== false){
                // if so, we found our image. set it as thumbnail
                set_post_thumbnail($post_id, $attachment->ID);
                // only want one image
                break;
            }
        }
    }
}

我试了很多教程,我在网上发现,没有任何效果。

请有这方面经验的人分享解决方案。

非常感谢

您需要先设置“特色图片”,然后再尝试查询。你试图做相反的事情。还要在 wp_insert_attachment 函数而不是参数中设置父 ID。

所以试试这个代码:

$new_post = array(
    'post_title'   => $title,
    'post_content' => $contents,
    'post_status'  => 'publish',
    'post_author'  => 1,
    'post_type'    => 'post'
);

$post_id = wp_insert_post($new_post);

$image = "https://fake.org/image.jpg";

$attachment_file_type = wp_check_filetype(basename($image), null);

$wp_upload_dir = wp_upload_dir();

$attachment_args = array(
    'guid'           => $wp_upload_dir['url'] . '/' . basename($image),
    'post_title'     => preg_replace('/\.[^.]+$/', '', basename($image)),
    'post_mime_type' => $attachment_file_type['type']
);

$attachment_id = wp_insert_attachment($attachment_args, $image, $post_id);

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

$attachment_meta_data = wp_generate_attachment_metadata($attachment_id, $image);

wp_update_attachment_metadata($attachment_id, $attachment_meta_data);

set_post_thumbnail($post_id, $attachment_id);

这是

的文档页面

wp_insert_attachment

参考:

https://developer.wordpress.org/reference/functions/wp_insert_attachment/#user-contributed-notes