Skip to content

Whitelist Dynamic URLs

Kevin Vess edited this page Dec 9, 2018 · 6 revisions

Below are examples of the different methods for whitelisting dynamic URLs:

Method 1 - Page URL Regardless of Query String

/**
 * Bypass Force Login to allow for exceptions.
 *
 * @param bool $bypass Whether to disable Force Login. Default false.
 * @return bool
 */
function my_forcelogin_bypass( $bypass ) {
    // Get visited URL without query string
    $url_path = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);

    // Allow URL
    if ( '/page-name/' === $url_path ) {
        $bypass = true;
    }

    // Allow filename URL
    if ( '/page-name.php' === $url_path ) {
        $bypass = true;
    }

    return $bypass;
}
add_filter( 'v_forcelogin_bypass', 'my_forcelogin_bypass' );

Method 2 - Page URL with Query String

/**
 * Bypass Force Login to allow for exceptions.
 *
 * @param bool $bypass Whether to disable Force Login. Default false.
 * @param string $url The visited absolute URL.
 * @return bool
 */
function my_forcelogin_bypass( $bypass, $url ) {
    $whitelist = array(
        home_url( '/page-name/?' . $_SERVER['QUERY_STRING'] ),
        home_url( '/page-name.php?' . $_SERVER['QUERY_STRING'] ),
    );

    if ( ! $bypass ) {
        $bypass = in_array( $url, $whitelist );
    }
    return $bypass;
}
add_filter( 'v_forcelogin_bypass', 'my_forcelogin_bypass', 10, 2 );

Method 3 - Page URL based on Query String Parameter(s) and/or Value(s)

/**
 * Bypass Force Login to allow for exceptions.
 *
 * @param bool $bypass Whether to disable Force Login. Default false.
 * @return bool
 */
function my_forcelogin_bypass( $bypass ) {
    // Allow URL if query string 'parameter' exists
    if ( isset( $_GET['parameter'] ) ) {
        $bypass = true;
    }

    // Allow URL where 'value' is equal to query string 'parameter'
    if ( $_GET['parameter'] == 'value' ) {
        $bypass = true;
    }

    return $bypass;
}
add_filter( 'v_forcelogin_bypass', 'my_forcelogin_bypass' );

Method 4 - Page URL within a Specified Directory

/**
 * Bypass Force Login to allow for exceptions.
 *
 * @param bool $bypass Whether to disable Force Login. Default false.
 * @return bool
 */
function my_forcelogin_bypass( $bypass ) {
    // Get visited URL without query string
    $url_path = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);

    // Allow any page URL within the specified directory
    if ( in_array( 'page-directory', explode( '/', $url_path ) ) ) {
        $bypass = true;
    }

    return $bypass;
}
add_filter( 'v_forcelogin_bypass', 'my_forcelogin_bypass' );
You can’t perform that action at this time.