There are times when we publish a file and add multiple images, but how do we make it so that unlogged in users (visitors) can only see one image? After the user logs in, he can see all the pictures in the article. Then this article introduces the following, modify the file code to achieve this effect, so that you can guide the user to register.
![Image[1]-WordPress Not logged in users (visitors) only show a picture in the article Used to guide the user to register - Photon Flux | Professional WordPress repair service, global, fast response](https://www.361sale.com/wp-content/uploads/2024/04/image-610.png)
First step, in the theme folder funtions.php(path /wp-content/themes/your-theme-name/funtions.php) add the following code to the file (end of file)
function remove_extra_images_from_content() {
// Get the current post ID
$post_id = get_the_ID();
// Get the content of the post
$content = get_the_content(); // Get the content of the post.
// Match all image addresses
preg_match_all('/
/i', $content, $matches);
// Remove all image tags except the first one
if ( count($matches) > 0 && count($matches[0]) > 1 ) {
for ( $i = 1; $i < count($matches[0]); $i++ ) {
$content = str_replace($matches[0][$i], '', $content);
}
}
// Return the content of the processed article
return $content;
}
![Image[2]-WordPress Not logged in users (visitors) only show a picture in the post Used to guide the user to register - Photon Flux | Professional WordPress repair service, global, fast response](https://www.361sale.com/wp-content/uploads/2024/04/Sunny_20240416_153110.png)
Step 2 Modify the singe.php file in the theme folder. (path /wp-content/themes/your-theme-name/singe.php)
File Editor Find
<?php the_content(); ?>
Replace it with the following code and you're good to go
<?php if ( ! is_user_logged_in() ) { echo remove_extra_images_from_content() ; } else { the_content(); } ?>
![Image[3]-WordPress Not logged in users (visitors) only show a picture in the post Used to guide users to register - Photon Flux | Professional WordPress repair service, global, fast response](https://www.361sale.com/wp-content/uploads/2024/04/image-611.png)
Link to this article:https://www.361sale.com/en/7994
The article is copyrighted and must be reproduced with attribution.
No comments