Skip to content

Instantly share code, notes, and snippets.

@bainternet
Forked from coagmano/User-Specific-Content.php
Created August 14, 2016 19:09
Show Gist options
  • Select an option

  • Save bainternet/dfd0f84c6c7d9ef7032d77a06a704142 to your computer and use it in GitHub Desktop.

Select an option

Save bainternet/dfd0f84c6c7d9ef7032d77a06a704142 to your computer and use it in GitHub Desktop.
Changes to User-Specific-Content WP plugin to remove unauthorised posts from The Loop
/*
These changes are for the plugin User-Specific-Content by Bainternet: https://wordpress.org/support/plugin/user-specific-content
The below adds the new filter to settings
*/
$p->add_field(array(
'label' => __('Filter posts from The Loop?','bauspc'),
'std' => false,
'id' => 'run_on_the_loop',
'type' => 'checkbox',
'section' => $setting,
'desc' => __('(check to stop posts appearing on archive / tags / category pages default unchecked)','bauspc')
)
);
<?php
/*
These changes are for the plugin User-Specific-Content by Bainternet: https://wordpress.org/support/plugin/user-specific-content
Add the below funciton inside the class bainternet_U_S_C
*/
/* Change Init */
public function U_S_C_init(){
$options = $this->U_S_C_get_option();
if ($options['run_on_the_content']){
/* hook the_content to filter users */
add_filter('the_content',array($this,'User_specific_content_filter'),20);
}
if ($options['run_on_the_excerpt']){
/* hook the_excerpt to filter users */
add_filter('the_excerpt',array($this,'User_specific_content_filter'),20);
}
// Here's the new stuff
if ($options['run_on_the_loop']){
/* hook pre_get_posts to filter posts by restrictions */
add_action('pre_get_posts', array($this, 'User_specific_loop_filter'));
}
//allow other filters
do_action('User_specific_content_filter_add',$this);
}
/**
* Remove posts from The Loop where user does not have required access
* Author: Fred Stark
* Author URI: https://github.com/coagmano
*/
public function User_specific_loop_filter($query){
if ( is_main_query() && !is_admin() && !is_singular() ) {
global $current_user;
get_currentuserinfo();
$args = array(
'relation' => 'OR',
array(
'key' => 'U_S_C_roles',
'compare' => 'NOT EXISTS'
)
);
if ( !empty( $current_user ) ) {
$roles = $current_user->roles;
foreach ($roles as $r) {
$args[] = array(
'key' => 'U_S_C_roles',
'value' => $r,
'compare' => 'LIKE'
);
}
}
$query->set('meta_query', $args);
return $query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment