如何在一次发帖中点击下载图片

时间:2013-03-14 作者:Angel

我有附件。php就是这样。

<?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\');  
}  
?> 
此代码将打印附件链接。

我的问题是:如何使这个链接成为一次点击下载图像并保存给计算机用户?

3 个回复
SO网友:whiteletters in blankpapers

可以使用插件:

http://wordpress.org/extend/plugins/download-shortcode/

我在这里帮助你,因为我在我的网站上使用了相同的功能(强制下载附件)

SO网友:tfrommen

虽然它不是特定于WP的,但以下是如何强制用户下载图像:

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: 代码未经测试。

SO网友:That Brazilian Guy

将以下内容另存为image.php 关于您的主题:

<?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;

结束