我在我的网站上显示来自其他网站的图像。URL保存在名为couv
.
我想将这些图片下载到我的网站上,并用新值创建一个新的自定义字段couv2
.
我在我的functions.php
但它不起作用。
function downloadcouv() {
global $wp_query;
$lien = get_post_meta(
$wp_query->queried_object->ID,
"couv",
true
);
$uploads = wp_upload_dir();
$reg = "#([^/]*)$#";
$chaine = $lien;
preg_match( $reg, $chaine, $res );
$couv = $uploads[\'baseurl\'] . \'/couv/\' . $res[1];
copy( $lien, $couv );
add_post_meta(
$wp_query->queried_object->ID,
"couv2",
$couv,
true
);
}
add_action( \'save_post\', \'downloadcouv\' );
编辑:我做了此更改,但仍不起作用。
function downloadcouv() {
global $wp_query;
$post_id = $wp_query->queried_object->ID;
$lien = get_post_meta(
$post_id,
"couv",
true
);
$desc = $post_title;
$couv = media_sideload_image(
$lien,
$post_id,
$desc
);
add_post_meta(
$post_title,
"couv2",
$couv,
true
);
}
add_action( \'save_post\', \'downloadcouv\' );
SO网友:Marc
这里有一个解决方案,可以将保存为自定义字段中URL的图像副本上载到站点的本地目录中。这不会将映像添加到媒体库中,更像是一种缓存机制。
在使用其他来源的图像之前,应始终确保您有权使用这些图像。Only use this code for good!
function downloadcouv( $post_id, $post, $update ) {
// Update the post\'s metadata.
if ( isset( $_POST[\'couv\'] ) ) {
// Get the upload directory
$upload_dir = wp_upload_dir();
// Make sure that the image URL is actually a URL
if ( FALSE !== filter_var($_POST[\'couv\'], FILTER_VALIDATE_URL) ) {
// Get the file extension
$ext = pathinfo($_POST[\'couv\'], PATHINFO_EXTENSION);
// Copy the file from the url to a local directory
copy( $backdrop, $upload_dir[\'basedir\'] . \'/site-img-\' . $post_id . \'.\' . $ext );
// Update the post meta with the URL to the uploaded image
update_post_meta( $post_id, \'couv2\', $upload_dir[\'basedir\'] . \'/site-img-\' . $post_id . \'.\' . $ext );
}
}
}
add_action( \'save_post\', \'downloadcouv\', 10, 3 );