you can use the_content filter hook to replace the hyperlink with login url.
following snippet should do the trick.
Update: this function should check if the user is logged in or not (my bad i forgot to add that)
add_action( "the_content", "restrict_url_in_post_content" );
function restrict_url_in_post_content() {
$loginUrl = sprintf( '<a href="https://wordpress.stackexchange.com/questions/251965/%s" class="some-class">%s</a>', wp_login_url( get_the_permalink() ), __( "You need to login to view this link", "text_domain" ) );
if( ! is_user_logged_in() )
$the_content = preg_replace( "/<a[^>]*>([^<]+)<\/a>/", $loginUrl, $the_content );
return $the_content;
}
Update:
Use following shortcode to have same effect on specific content.
Uses: [restricted]<a href="#">url</a>[/restricted]
function restricted_content( $atts , $content = null ) {
$atts = shortcode_atts(
array(
'show_login' => '1',
'message' => __( "You need to login to view this", "text_domain" ),
'login_redirect' => get_the_permalink(),
),
$atts,
'restricted'
);
$loginUrl = sprintf( '<a href="https://wordpress.stackexchange.com/questions/251965/%s" class="some-class">%s</a>', wp_login_url( $atts["login_redirect"] ), $atts["message"] );
if( is_user_logged_in() ) {
return $content;
} else if( $atts["show_login"] == 1 ) {
return $loginUrl;
} else {
return $atts["message"];
}
}
add_shortcode( 'restricted', 'restricted_content' );