1

In WordPress, I use a function in functions.php to only not show certain posts(by category) if a user is not signed in:

   function my_filter( $content ) {

    $categories = array(
        'news',
        'opinions',
        'sports',
        'other',
    );

    if ( in_category( $categories ) ) {
        if ( is_logged_in() ) {
            return $content;
        } else {
            $content = '<p>Sorry, this post is only available to members</p> <a href="gateblogs.com/login"> Login </a>';
            return $content;
        }
    } else {
        return $content;
    }
}
add_filter( 'the_content', 'my_filter' );

I use a plugin(not important to my question), but basically, I can use something like https://gateblogs.com/login?redirect_to=https%3A%2F%2Fgateblogs.com%2Ftechnology%2Flinux-tutorials%2Fsending-mail-from-server to redirect to a page after a successful login. How can I get a post's URL and apply it into the sign up link.

Note: The function is originally from this question.

2

You can do a conditional and return the post's URL by using a get_the_permalink() in conjunction with is_single():

add_filter( 'the_content', 'my_filter' );

function my_filter( $content ) {

     // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {
        return $content . get_the_permalink();
    }

    return $content;
}
  • 1
    I came up with a different solution, which I will post in a bit. However, the get_the_permalink() function you used helped a lot. – NerdOfLinux Jul 25 '17 at 20:36
  • Happy to hear I could be of service. @NerdOfLinux – Jack Johansson Jul 25 '17 at 20:38
1

I figured out how to do it with the get_the_permalink() function:

/* Protect Member Only Posts*/
function post_filter( $content ) {

    $categories = array(
        'coding',
        'python',
        'linux-tutorials',
        'swift',
        'premium',
    );
    if ( in_category( $categories ) ) {
        if ( is_user_logged_in() ) {
            return $content;
        } else {
            $link = get_the_permalink();
            $link = str_replace(':', '%3A', $link);
            $link = str_replace('/', '%2F', $link);
            $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>";
            return $content;
        }
    } else {
         return $content;
    }
}
add_filter( 'the_content', 'post_filter' );

Please note than the str_replace is because I has to change the link for the plugin to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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