如何从媒体库中设置帖子的特色图像

时间:2018-06-15 02:46:56

标签: wordpress image programmatically featured

如果我使用此函数以编程方式创建帖子:

function write_post_with_featured_image($post_title, $categories) {
        $category_names_array = explode(",", $categories);

        $category_ids = array();
        foreach ($category_names_array as $category_name) {
            $category_id = get_cat_ID($category_name);
            array_push($category_ids, $category_id);
        }

        // Create post object
        $my_post = array(
          'post_title'    => wp_strip_all_tags($post_title),
          'post_status'   => 'publish',
          'post_author'   => 1,
          'post_category' => $category_ids
        );


        // Insert the post into the database
        $post_id=wp_insert_post( $my_post );
        echo "post_id:" . $post_id;

    }

如何以编程方式设置媒体库中已存在的精选图像?

1 个答案:

答案 0 :(得分:0)

希望每个人都会喜欢这个创建帖子的功能,并从媒体库中设置它的特色图片:

function write_post_with_featured_image($post_title, $categories, $image_in_library_url) {
        $category_names_array = explode(",", $categories);

        $category_ids = array();
        foreach ($category_names_array as $category_name) {
            $category_id = get_cat_ID($category_name);
            array_push($category_ids, $category_id);
        }

        // Create post object
        $my_post = array(
          'post_title'    => wp_strip_all_tags($post_title),
          'post_status'   => 'publish',
          'post_author'   => 1,
          'post_category' => $category_ids
        );


        // Insert the post into the database
        $post_id=wp_insert_post( $my_post );
        echo "post_id:" . $post_id;

        //Get Image Attachment Id
        $attachment_id = attachment_url_to_postid( $image_in_library_url );
        echo "attachment_id:" . $attachment_id;

        // And finally assign featured image to post
        set_post_thumbnail( $post_id, $attachment_id );
        echo "featured image added";
    }
}

$post_title = 'My Super Post';
$categories = 'Category1,Category2';
$image_in_library_url = "http://localhost/wp-content/uploads/2018/06/my-super-image.jpg";
write_post_with_featured_image($post_title,$categories,$image_in_library_url);