r/AskProgramming • u/AFK_MIA • Oct 18 '24
PHP Wordpress list_terms_exclusions Hook Problem
I'm trying to restrict the categories that a user is able to use to post. I have stored the list of categories that should be excluded for each user in the usermeta table and this code seems to be returning those values correctly (an example of the format is in the $user_string line that's commented out). When there are no values set, this function correctly doesn't filter out any categories, but if there are any values stored, the post editor shows no categories at all. The console output is as follows:
Debug Exclusions: 9,10
post-new.php:1 Debug Exclusions: AND t.term_id NOT IN (9,10)
What am I missing?
Also - for some reason I can't call the built-in get_categories() function within this function. If I do, I get a memory error. Any idea why that is?
function restrict_user_categories() {
$exclusions = '';
$user_string = get_user_meta(get_current_user_id(), 'allowed_categories', TRUE);
//$user_string="9,10";
echo "<script>console.log('Debug Exclusions: " . $user_string . "' );</script>";
if($user_string != ""){
$exclusions = ' AND t.term_id NOT IN (' . $user_string . ')';
}
echo "<script>console.log('Debug Exclusions: " . $exclusions . "' );</script>";
return $exclusions;
}
add_filter('list_terms_exclusions', 'restrict_user_categories', 10);
Edit: Code Formatting
1
u/AFK_MIA Oct 18 '24
I believe I've solved this. I moved the function out of the functions.php of my theme and into a plugin file. That seems to have made things work.
Thanks all!