如何上传图片并返回图片ID?

时间:2016-11-24 作者:Rick Groen

我需要从url导入图像并返回图像id

有可能生成这样的函数吗?

    <?php
$link = \'https://mosaic01.ztat.net/vgs/media/pdp-zoom/NI/11/3D/03/4D/11/NI113D034-D11@12.jpg\';
$title = \'the image title\';
$alt = \'the image alt\';

$image_id = insert_image($link, $title, $alt);

?>

2 个回复
最合适的回答,由SO网友:jgraup 整理而成

查看侧面加载图像。media_sideload_image()/wp_handle_sideload() 并从URL获取ID。attachment_url_to_postid.

<?php

$url = "http://wordpress.org/about/images/logos/wordpress-logo-stacked-rgb.png";
$title = "Some Image Title";
$alt_text = "Some Alt Text";

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

// sideload the image --- requires the files above to work correctly
$src = media_sideload_image( $url, null, null, \'src\' );

// convert the url to image id
$image_id = attachment_url_to_postid( $src );

if( $image_id ) {

    // make sure the post exists
    $image = get_post( $image_id );

    if( $image) {

        // Add title to image
        wp_update_post( array (
            \'ID\'         => $image->ID,
            \'post_title\' => "Some Image Title",
        ) );

        // Add Alt text to image
        update_post_meta($image->ID, \'_wp_attachment_image_alt\', $alt_text);
    }
}

SO网友:Felipe Rodrigues

什么id?HTML ID?如果没有,也许你需要一个正则表达式来搜索url,以便找到一个可以指定为id的模式。这个问题有点困惑,你能给我一个简单的解释吗?

相关推荐

插件“WP Attachments”在_Content之后输出,我怎样才能最好地更改位置?

我正在使用插件;WP附件;在帖子上显示附加的媒体文件。该插件似乎无法在我的模板中手动调用列表,我认为该插件不再受到支持。我签入了插件代码,我认为下面这行是关键。add_filter(\'the_content\', \'wpatt_content_filter\'); 我的编码能力有限,但我基本上将“内容”更改为“附件文件”,并在我的函数中进行了更改。我添加的php:function the_attachedfiles( $more_link_text = null, $strip_teaser