限制 WordPress 中的用户使用自定义 post 类型访问定义的 post

Limit users in WordPress to access defined post with custom post type

我构建了一个插件,它需要允许管理员使用 post ID 和自定义 post 类型排除用户阅读某些特殊内容。

一般来说,如果某些 post 的 ID 99 具有自定义 post 类型 lesions 并且管理员选择将其排除,如果继续直接 link 也没有在列表中看到 post。

注意:我不需要制作循环,我需要通过一些挂钩、过滤器或操作以某种方式影响 WP_Query 上具有特定自定义 post 类型的其他插件。

我还没来得及测试呢。但它应该可以工作。 这个想法是在 wp_options 中保存 post id 和 post 类型。然后你可以得到这些值并将它们保存在一个数组中。之后,您将它们与当前 post 进行比较并执行您想要的操作。你可以把它放在 functions.php

function sr_excluded_users()
{
    global $post;
    global $wp_query;
    $exclusive_post_ids = array(); // List of post ids ( you can store it in wp options )
    $exclusive_post_types = array(); // List of custom post types ( you can store it in wp options )
    if( in_array( $post->ID, $exclusive_post_ids ) && in_array( $post->post_type, $exclusive_post_types ) )
    {        
        $wp_query->set_404();
        status_header( 404 );
        get_template_part( 404 ); 
        exit();
    }
}
add_action( 'wp', 'sr_excluded_users' );

编辑: 从循环中删除 posts 的函数

function sr_excluded_users_loop($query) 
{
    $exclusive_post_ids = array(); // List of post ids ( you can store it in wp options )
    $query->set( 'post__not_in' , $exclusive_post_ids );
}
add_action( 'pre_get_posts', 'sr_excluded_users_loop' );