0

I am trying to show a weblink to my WordPress users only if they are logged in. If they are logged out they will see text that says they need to "Login to View"

My Original Code

<a href="<?php echo get_post_meta($post_id, 'external_link', true); ?>">View Website</a>

My Altered Code

    <a href="<?php
if ( is_user_logged_in() ) {
    echo get_post_meta($post_id, 'external_link', true);
} else {
    echo 'Login to View';
}
?>">View Website</a>

When a user is logged in, it's doing what it's supposed to but when they are logged out the url is broken. Can someone post an example of the format that it should be done?

closed as off-topic by Rarst, cjbj, Jack Johansson, Max Yudin, Robert hue Jun 19 '17 at 8:42

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • You are trying to output text of your message as the URL (which it's not). I would recommend some time with PHP docs, this isn't really WP issue. :) – Rarst Jun 15 '17 at 9:10
1

The code you posted:

 <a href="<?php
    if ( is_user_logged_in() ) {
        echo get_post_meta($post_id, 'external_link', true);
    } 
    else {
        echo 'Login to View';
    }
   ?>
 ">View Website</a>

Is going to echo "Login to View" as the href attribute.

You need something more like:

    <a href="<?php
        if ( is_user_logged_in() ) {
           echo get_post_meta($post_id, 'external_link', true);
        } 
       else {
          echo wp_login_url( get_permalink() );
}
?>">View Website</a>

That of course won't be changing the text, just the href. So maybe do the conditional a step earlier (I added an arbitrary <span> for context):

<span> 
<?php 
if ( is_user_logged_in() ) {
   $href = esc_url( get_post_meta($post_id, 'external_link', true ) );
   $text = 'View Website'; 
}
else {
    $href = wp_login_url( get_permalink() );
    $text = 'Login to View';
}
?>
<a href="<?php echo $href; ?>" ><?php echo $text; ?></a>
</span>

Since you're pulling the url from the db, I wrapped it in esc_url() for sanitization.

  • Exactly what I was looking for. Great to learn from. – Tim44 Jun 15 '17 at 2:01
0

Here's what you need:

<?php
if ( is_user_logged_in() ) {
    echo '<a href="'.get_post_meta($post_id, 'external_link', true).'">View Website</a>';
} else {
    echo '<a href="'.wp_login_url(get_permalink()).'">Login to view Website</a>;
}
?>

Not the answer you're looking for? Browse other questions tagged or ask your own question.