How to single click to download image in single post

i have attacment.php like this.

<?php  

if ( $attachments = get_children( array(  
'post_type' => 'attachment',  
'post_mime_type'=>'image',  
'numberposts' => 1,  
'post_status' => null,  
'post_parent' => $post->ID  
)));
foreach ($attachments as $attachment) {  
echo wp_get_attachment_link( $attachment->ID, '' , false, true, 'Download This Wallpaper');  
}  
?> 

this code will print attachment link.

Read More

My question is: How to make this link to be single click to download image and save to computer user?

Related posts

Leave a Reply

3 comments

  1. Although it is not WP-specific, here’s how to force the user to download an image:

    if ( $attachments = get_posts( array(
        'post_type' => 'attachment',
        'post_mime_type'=>'image',
        'numberposts' => -1,
        'post_status' => 'any',
        'post_parent' => $post->ID,
    ) ) );
    foreach ( $attachments as $attachment ) {
        echo '<a href="javascript:void(0);"
            onclick="document.execCommand('SaveAs', true, '' . get_permalink( $attachment->ID ) . '');">
            Download This Wallpaper</a>';
    }
    

    Note: the code is untested.

  2. Save the following as image.php on your theme:

    <?php
    
    // This forces all image attachments to be downloaded instead of displayed on the browser.
    // For it to work, this file needs to be called "image.php".
    // For more info, refer to the wp hierarchy diagram.
    
    // Get the path on disk. See https://wordpress.stackexchange.com/a/20087/22510
    global $wp_query;
    $file = get_attached_file($wp_query->post->ID);
    
    // Force the browser to download. Source: https://wpquestions.com/7521
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: public'); //for i.e.
    header('Pragma: public');
    
    // ob_clean(); // Looks like we don't need this
    flush();
    readfile($file);
    exit;