ワードプレスのis_post_status_viewableフィルタの使用方法・解説

概要

is_post_status_viewableフィルタは、投稿ステータスが公開状態か調べるために使用されます。主に、投稿時の公開状況を確認するためのフィルタで、特定の条件下で投稿を表示・非表示にする際に役立ちます。このフィルタを利用することで、特定のユーザーやグループに対してのみ投稿が閲覧可能かどうかを制御することができます。

主な機能の利用例

  1. カスタム権限を持つユーザーのための投稿表示制御
  2. 特定の条件に基づく投稿のカスタム可視性設定
  3. フロントエンドでの投稿表示のカスタマイズ
  4. 投稿内容が存在する場合にのみ表示
  5. 投稿のステータスに応じたユーザーへのメッセージ表示
  6. APIを介して投稿を取得する際の可視性管理
  7. 検索結果に基づく投稿のフィルタリング
  8. お知らせやイベントの公開ステータス管理

構文

add_filter('is_post_status_viewable', 'my_custom_viewable_filter', 10, 2);

パラメータ

  • $is_viewable (bool): 現在の投稿ステータスが表示可能かどうか。
  • $post (WP_Post): 状態が確認される投稿オブジェクト。

戻り値

  • (bool): 投稿が表示可能な場合は true、そうでない場合は false

関連する関数

is_post_status_viewable

使用可能なバージョン

WordPress 4.1.0 以降で使用可能です。

ワードプレスのコアファイルのパス

wp-includes/post.php

この関数のアクションでの使用可能性

アクション 使用可能性
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプルコード 1: 投稿の可視性をカスタマイズする

add_filter('is_post_status_viewable', 'custom_post_viewable', 10, 2);
function custom_post_viewable($is_viewable, $post) {
    if ($post->post_type == 'my_custom_post_type') {
        return false; // カスタム投稿タイプは非表示
    }
    return $is_viewable; // それ以外は元の可視性を返す
}

このコードは、カスタム投稿タイプ my_custom_post_type の場合、投稿の表示を無効にします。

サンプルコード 2: 特定のユーザーのみ表示可能

add_filter('is_post_status_viewable', 'restricted_viewable_for_role', 10, 2);
function restricted_viewable_for_role($is_viewable, $post) {
    if (!current_user_can('administrator') && $post->post_status == 'private') {
        return false; // 管理者以外は非表示
    }
    return $is_viewable;
}

このコードは、非公開の投稿を管理者以外のユーザーには表示しないを実装します。

サンプルコード 3: カスタムメッセージの表示

add_filter('is_post_status_viewable', 'custom_message_for_private', 10, 2);
function custom_message_for_private($is_viewable, $post) {
    if ($post->post_status == 'private' && !is_user_logged_in()) {
        echo "この投稿はログインしたユーザーのみに表示されます。";
        return false;
    }
    return $is_viewable;
}

このコードは、非公開投稿に対して、ログインしていないユーザーにメッセージを表示します。

サンプルコード 4: APIリクエストでの可視性判定

add_filter('is_post_status_viewable', 'api_post_visibility_check', 10, 2);
function api_post_visibility_check($is_viewable, $post) {
    if (defined('REST_REQUEST')) {
        return $post->post_status === 'publish'; // REST API経由では公開のみ表示
    }
    return $is_viewable;
}

このコードは、REST APIリクエストに対して、公開投稿のみを表示するようにします。

サンプルコード 5: 検索結果に基づくフィルタリング

add_filter('is_post_status_viewable', 'search_filter_for_visible_posts', 10, 2);
function search_filter_for_visible_posts($is_viewable, $post) {
    if (is_search() && $post->post_status != 'publish') {
        return false; // 検索結果に非公開投稿を表示しない
    }
    return $is_viewable;
}

このコードは、検索結果に対して、非公開の投稿を表示しないようにします。

この関数について質問する


上の計算式の答えを入力してください