Skip to content

Instantly share code, notes, and snippets.

@ixkaito
Created August 9, 2014 18:08
Show Gist options
  • Save ixkaito/82eb4e5952b3d9028e6f to your computer and use it in GitHub Desktop.
Save ixkaito/82eb4e5952b3d9028e6f to your computer and use it in GitHub Desktop.
<?php
function my_must_login_pages() {
if ( is_feed() ) // フィードの時は除外
return;
$loginflg = false; // 条件が増えてもいいようにフラグを作っておく。 デフォルトはfalse
if ( is_singular( 'works' ) && has_term( 'private', 'category' ) ) { // カスタム投稿タイプ works の個別記事でかつカスタムタクソノミー works_cat で タームが private
$loginflg = true;
} elseif ( is_tax( 'works_cat', 'private' ) ) { // もしくはカスタムタクソノミー works_cat のターム private のアーカイブ
$loginflg = true;
}
if ( !is_user_logged_in() && $loginflg ) { // $loginflg が true で WordPressにログインしてなかったら
// ログイン画面へ遷移させる戻り先はその直前に見ていたページ
// http://codex.wordpress.org/Function_Reference/auth_redirect
auth_redirect();
}
}
add_action( 'wp', 'my_must_login_pages' );
// get_header よりもはっやい段階で実行。
// クエリからWPオブジェクトが作られて(表示する内容が決まって)、テンプレートが表示される前
// でもこのままだと管理者もそのページにリダイレクトされるねん!
// 管理者はダッシュボードにリダイレクトさせたいねん!
// http://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect
function my_login_redirect( $redirect_to, $request, $user ) {
// is there a user to check?
global $user;
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
// 管理者かどうかチェック
if ( in_array( 'administrator', $user->roles ) ) {
// ダッシュボードにリダイレクト
// http://codex.wordpress.org/Function_Reference/admin_url
return admin_url();
} else {
// redirect them to the default place
return $redirect_to;
}
} else {
return $redirect_to;
}
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
// 他のところではタイトルだけチラ見せして本文は自分で決めた文言に置き換えたいねん!
// おっと抜粋の場合もあるよね!
// http://codex.wordpress.org/Plugin_API/Filter_Reference/the_content
function my_the_content_filter($content) {
$loginflg = false;
if ( has_term( 'private', 'category' ) ) {
$loginflg = true;
}
if ( !is_user_logged_in() && $loginflg ) {
$content = 'ろぐいんせーや';
}
return $content;
}
add_filter( 'the_content', 'my_the_content_filter' );
add_filter( 'get_the_excerpt', 'my_the_content_filter' );
// フィードの存在を忘れてはいけないよ!
// 全文か抜粋かはダッシュボードから変えられるし!
function my_content_feed( $content ) {
if ( has_term( 'private', 'category' ) ) {
$content = 'ろぐいんせーや';
}
return $content;
}
add_filter('the_content_feed', 'my_content_feed', 10, 2);
add_filter('the_excerpt_rss', 'my_content_feed', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment