Skip to content

Instantly share code, notes, and snippets.

@grakic
Last active August 29, 2015 14:16
Show Gist options
  • Save grakic/4a57d0c1c6fdbf9e123b to your computer and use it in GitHub Desktop.
Save grakic/4a57d0c1c6fdbf9e123b to your computer and use it in GitHub Desktop.
Simple WordPress plugin to require login for site access, showing welcome content on frontpage for non-authenticated users. Uses personalized links to authorize access to feeds.
<?php
/*
Plugin Name: Require Login
Plugin URI:
Author: Goran Rakic
Version: 2.0
Author URI: http://blog.goranrakic.com
*/
/**
* If user is not logged in display a static welcome page.
* Allow access to feeds if feedkey is provided.
* Else redirect to login page.
*/
function require_login_redirect()
{
if (!is_user_logged_in()) {
if (is_front_page()) {
/* FIXME: Show welcome page
Load custom welcome page here (can be set with options api)
or include any other static content...
*/
require(ABSPATH . '/static.php');
exit;
} elseif (is_feed() && isset($_GET['feedkey']) && feedkey_check($_GET['feedkey'])) {
return; // do not redirect for feeds if feedkey is valid
}
auth_redirect(); // redirect if not logged in
}
}
add_action('template_redirect', 'require_login_redirect', 1);
/**
* Add feedkey to all feed links
*/
function require_login_add_feedkey($url)
{
$uid = get_current_user_id();
return add_query_arg(array('feedkey' => feedkey_gen($uid)), $url);
}
add_filter('feed_link', 'require_login_add_feedkey');
add_filter('post_comments_feed_link', 'require_login_add_feedkey');
add_filter('category_feed_link', 'require_login_add_feedkey');
add_filter('author_feed_link', 'require_login_add_feedkey');
add_filter('tag_feed_link', 'require_login_add_feedkey');
add_filter('search_feed_link', 'require_login_add_feedkey');
// FIXME: Use password_hash/password_verify for PHP>=5.5
function feedkey_gen($uid)
{
return $uid . '-' . md5(wp_salt('auth') . $uid);
}
function feedkey_check($feedkey)
{
$uid = substr($feedkey, 0, strpos($feedkey, '-'));
return feedkey_gen($uid) === $feedkey;
}
/**
* By default redirect to homepage after login
*/
function require_login_admin_default_page($redirect_to, $request, $user)
{
if (isset($_GET['redirect_to']))
return $_GET['redirect_to'];
if ($redirect_to == admin_url())
return home_url();
return $redirect_to;
}
add_filter('login_redirect', 'require_login_admin_default_page');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment