phpwordpresschild-theming

Check for URL in WordPress functions.php


I want to restrict access to a specific URL of my WordPress-Site for logged-in users only. So if someone isnt logged in, they should be redirected to homepage.

I guess its working with this code in functions.php

if (!(is_user_logged_in()) && is_page('PAGE-ID')){
    wp_redirect( home_url() . '/login' );
    exit;
}

But unfortunately this site has no Page-ID, so I have to target the URL instead. How can I do this?


Solution

  • Try like this.

    global $post;
    $pageUrl = get_permalink($post->ID);
    
    if (!(is_user_logged_in()) && $pageUrl=='http://yoursiteurl.com/page/'){
        wp_redirect( home_url() . '/login' );
        exit;
    }