Hide images from guests in Wordpress!

0

If need to hide images from guests (users that are not registered) on your Wordpress blog this function should help.

Why would I need to hide images from guests?

You may have some images that you only want registered users to view on your blog. For example, you may be a photographer that would like to show your latest great shot to a select number of registered users. Making content available to registered only users can be a great incentive for your readers to register on your blog.

Simple add the below code to the top of your theme’s functions.php after the opening php tag.

PHP Function / Hide images

if ( is_user_logged_in() ) {

} else {
	add_filter('the_content','wpi_image_content_filter',11);

function wpi_image_content_filter($content){

    if (is_single() || is_front_page || is_home ()){
      $content = preg_replace("/]+\>/i", "" />", $content);

    }

    return $content;
}
}

Please note: the function will not block image links, so guests could still view the source image if they click on the image. To avoid this do not add links to inserted images.

Alternatively, use the below function to block images and links. Be careful, as this will remove (hide) all links in your blog posts.

PHP Function / Hide images and links

if ( is_user_logged_in() ) {

} else {
	add_filter('the_content','wpi_image_content_filter',11);

function wpi_image_content_filter($content){

    if (is_single() || is_front_page || is_home ()){
      $content = preg_replace("/]+href[^>]+>/", "", $content);
      $content = preg_replace("/]+\>/i", "" />", $content);

    }

    return $content;
}
}

Tags:

No Responses | Add

  1. Will

    Today

    Be the first to leave a comment!

Got something to say?

If would like to enquire about any of my services please use the contact form, as your enquiry will reach me quicker that way.