How to redirect the WORDPRESS hotlink (for exp: Image.jpg) to the post / page where it is?

Google recently changed its image search and as a result, most of the traffic clicked over the original image and sent it to a direct image file.

I changed my .htaccess and stopped all hotlinks and redirected to my home page if they click on the image file.

I recently also tried if it is possible to redirect the post or page where the image is located.

The following code

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

      

But it redirects to http://www.mydomain.com/?attachment_id=

id is zero or cannot get the correct id

My site in Wordpress CMS version 3.5.1

can anyone help how to redirect to the correct attachment page to directly request the .jpg file.

Thank you in advance

+3


source to share


1 answer


Your code would only work if the requested url had an ID parameter that would be an exact match to the image url like http://www.example.com/?id=http://www. example.com/uploads/Some-Image.jpg

This is true? However, you shouldn't use id

as this is a reserved setting for other things in WP. In your .htaccess you have to redirect http://www.example.com/uploads/Some-Image.jpg for example http://www.example.com/?image_redirect=http://www.example.com/ uploads / Some-Image.jpg . Then use $imageURL = $_GET['image_redirect']

.



Other notes: strip_tags

does not make the string safe to use as a SQL query. In WordPress, you have esc_sql($string)

. Also, you should use if ( $imageUrl != '' )

instead !==

. And there is an error on line 5, it should say $wpdb->get_row

you currently have a minus sign. I assume these are typos. Finally, you shouldn't use Location:

a 404 header .

0


source







All Articles