Skip to main content
3 of 4
Fixes Readability
kaiser
  • 50.8k
  • 27
  • 150
  • 244

Download external images with function

Actually, i display images on my site from other sites. Url is on a custom field name "couv" I'd like to download theses pictures on my site and create a new custom field with the new value "couv2" I tried to do this with a function in my functions.php with the following code. But it doesn't work. Where did i make a mistake ? Thanks for your help.

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

Edit : I change it like this, but no way...

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' );
Guenfood
  • 61
  • 1
  • 5