The code you posted:
<a href="https://wordpress.stackexchange.com/questions/270167/<?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="https://wordpress.stackexchange.com/questions/270167/<?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="https://wordpress.stackexchange.com/questions/270167/<?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.