限制WordPress中的用户访问具有自定义帖子类型的已定义帖子

时间:2017-03-23 20:32:23

标签: php wordpress user-controls custom-post-type

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

通常,如果某些帖子的ID为99且自定义帖子类型为lesions,并且管理员选择要排除,则用户在获取直接链接时获取404,并且也不会在列表中看到该帖子。

注意:我不需要进行循环,我需要通过某些钩子,过滤器或操作以某种方式影响WP_Query上的其他插件和特定的自定义帖子类型。

1 个答案:

答案 0 :(得分:1)

我没有时间测试它。但它应该工作。这个想法是在wp_options中保存post id和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' );

修改:从循环中删除帖子的功能

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' );