如何将WORDPRESS热链接图像(对于exp:Image.jpg)重定向到发布/页面所在的位置?

时间:2013-02-09 03:51:53

标签: image wordpress redirect

最近谷歌更改图片搜索,因此大部分流量点击查看原始图片,然后将其发送到直接图片文件。

我已更改了我的.htaccess并停止了所有热链接并重定向到我的主页,如果他们点击图片文件。

最近我也试过,如果可以重定向到图片所在的帖子或页面。

通过以下代码

<?php 
require('../wp-blog-header.php');
$imageURL = strip_tags( $_GET['id'] );
if imageURL!== "") {    
  $query = "SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment'AND post_parent > '0' AND guid = '$imageURL'";    
  $linkedImage = $wpdb-get_row($query);    
  $attachmentUrl = get_attachment_link($linkedImage->ID);    
  if($attachmentUrl !== "" && !is_numeric(stripos($attachmentUrl, "attachment_id=0"))) {
    header("HTTP/1.1 302 Found");        
    header("Location: ". $attachmentUrl);        
    exit;    
  }
}
$newUrl = get_site_url() . "/image-not-found";
header("HTTP/1.0 404 Not Found");
header("Location: " . $newUrl);
exit;
?>

但它重定向到http://www.mydomain.com/?attachment_id=

id为nil或无法获取正确的ID

我在Wordpress CMS版本3.5.1中的网站

任何人都可以帮助如何重定向到.jpg文件直接请求的正确附件页面。

提前致谢

1 个答案:

答案 0 :(得分:0)

只有在请求的网址上有ID参数与图片网址完全匹配时,您的代码才有效,例如http://www.example.com/?id=http://www.example.com/uploads/Some-Image.jpg

是这样的吗?即便如此,您也不应该使用id,因为它是WP中其他内容的保留参数。在.htaccess中,您应该将http://www.example.com/uploads/Some-Image.jpg重定向到例如http://www.example.com/?image_redirect=http://www.example.com/uploads/Some-Image.jpg。然后使用$imageURL = $_GET['image_redirect']

其他注意事项:strip_tags不能使字符串安全地用作SQL查询。在WordPress中,你有esc_sql($string)。此外,您应该使用if ( $imageUrl != '' ),而不是!==。第5行有一个错误,应该说$wpdb->get_row,你现在有一个减号。我认为这些都是拼写错误。最后,您不应将Location:标头与状态代码404一起使用。