简体   繁体   中英

Restrict php code to logged in users - Wordpress

I've got a gallery on a listing page that I want to only display to logged in users. I'm trying to use the function is_user_logged_in() but I'm failing to work out exactly how to implement it.

I'm a beginner trying to work more in the PHP files rather than plugins/shortcodes.

This is the code, how would I add the is_user_logged_in() so the gallery only displays to logged in users?:

<?php
//get the listing gallery
$photos = listable_get_listing_gallery_ids();
if ( ! empty( $photos ) ) : ?>

<div class="entry-featured-carousel">
    <?php if ( count( $photos ) == 1 ):
        $myphoto = $photos[0];
        $image = wp_get_attachment_image_src( $myphoto, 'listable-featured-image' );
        $src = $image[0]; ?>
        <div class="entry-cover-image" style="background-image: url(<?php echo listable_get_inline_background_image( $src ); ?>);"></div>
    <?php else: ?>
        <div class="entry-featured-gallery">
            <?php foreach ( $photos as $key => $photo_id ):
                $src = wp_get_attachment_image_src( $photo_id, 'listable-carousel-image' ); ?>
                <img class="entry-featured-image" src="<?php echo $src[0]; ?>" itemprop="image" />
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
<?php endif; ?>

Well since you know you only want to find photos when a user is logged in I would use a Ternary Operators . Which looks like this:

$var = test ? true : false;

For your code above I would implement it like this:

$photos = is_user_logged_in() ? listable_get_listing_gallery_ids(): '';

So the check for the is_user_logged_in is completed, if the answer returned is true, the process of listable_get_listing_gallery_ids is completed. If the process of is_user_logged_in returns false, $photos is set to an empty string.

This saves you computational time for not wasting effort on querying the database, when you plan to disregard the information. The link I provided above actually uses an example with the scenario of $user->is_logged_in()

is_user_logged_in() function returns a boolean ( true or false ): see WordPress Developer documentation here: https://developer.wordpress.org/reference/functions/is_user_logged_in/

In your case you can add the boolean next to your checking of empty photos logic.

if( ! empty( $photos ) && is_user_logged_in() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM