WordPress not logged in users (visitors) only show a picture in the article Used to guide users to register

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.

WordPress not logged in users (visitors) only show a picture in the article Used to guide users to register

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;
}
WordPress not logged in users (visitors) only show a picture in the article Used to guide users to register

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(); } ?>
WordPress not logged in users (visitors) only show a picture in the article Used to guide users to register

Contact Us
Can't read the article? Contact us for a free answer! Free help for personal, small business sites!
Tel: 020-2206-9892
QQ咨询:1025174874
(iii) E-mail: info@361sale.com
Working hours: Monday to Friday, 9:30-18:30, holidays off
Posted by photon fluctuations, retweeted with attribution:https://www.361sale.com/en/7994/

Like (2)
Previous April 16, 2024 3:12 pm
Next April 16, 2024 3:52 pm

Recommended

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

020-2206-9892

QQ咨询:1025174874

E-mail: info@361sale.com

Working hours: Monday to Friday, 9:30-18:30, holidays off

Customer Service
In order to facilitate global user registration and login, we have canceled the telephone login function. If you encounter login problems, please contact our customer service for assistance in binding your email address.