Skip to content

Bypass Dynamic URLs

Kevin Vess edited this page Nov 9, 2020 · 1 revision

Below are examples of the different methods for allowing dynamic URLs to be publicly accessible:

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 $visited_url The visited absolute URL.
 * @return bool
 */
function my_forcelogin_bypass( $bypass, $visited_url ) {
    $allowed = array(
        home_url( '/page-name/?' . $_SERVER['QUERY_STRING'] ),
        home_url( '/page-name.php?' . $_SERVER['QUERY_STRING'] ),
    );
    if ( ! $bypass ) {
        $bypass = in_array( $visited_url, $allowed );
    }
    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' );