Home > Blockchain >  Using href within IF condition
Using href within IF condition

Time:11-01

This code works perfectly:

<a href="<?php global $current_user; echo home_url() . '/members/' . $current_user->user_login . '/profile/edit/group/2/'; ?>">My Next Adventure</a>

but when I try to use it in an IF condition, it doesn't work.

What am I doing wrong?

Thanks, Dror

This is the code that doesn't work:

<?php

if (is_user_logged_in()) {
<a href="<?php global $current_user; echo home_url() . '/members/' . $current_user->user_login . '/profile/edit/group/2/'; ?>">My Next Adventure</a>
} else {
echo "Please sign in to list your next adventure!";
}

?>

CodePudding user response:

There have been 2 PHP-tags missing surrounding the HTML link element:

<?php

if (is_user_logged_in()) { ?>
<a href="<?php global $current_user; echo home_url() . '/members/' . $current_user->user_login . '/profile/edit/group/2/'; ?>">My Next Adventure</a>
<?php } else {
echo "Please sign in to list your next adventure!";
}

?>

CodePudding user response:

If you want to print an HTML tag, it has to be outside of PHP tags, or you have to use a language construct like echo or print.

In your example, you can do it like that:

<?php if (is_user_logged_in()) { ?>

<a href="<?php global $current_user; echo home_url() . '/members/' . $current_user->user_login . '/profile/edit/group/2/'; ?>">My Next Adventure</a>

<?php } else { ?>

Please sign in to list your next adventure!

<?php } ?>

A cleaner way to write this would be like this:

<?php

global $current_user;

$href = home_url() . '/members/' . $current_user->user_login . '/profile/edit/group/2/';

echo (is_user_logged_in()) ? '<a href="'.$href.'">My Next Adventure</a>' : 'Please sign in to list your next adventure!';
  • Related