I've got the code working after a lot of fiddling and googling, but I have a strong suspicion that there is a much better way to accomplish what I'm doing. Is this a place where I can ask for help to clean up and improve my code? If so, thanks in advance!
This code is modifying a wordpress loop.
The goal: Check the roles of the current user and show posts of certain categories, based on the user roles.
My working code:
/** Check if the current user is a Student, and if they are, run the custom loop. */
$current_user = wp_get_current_user();
$roles = $current_user->roles;
if ($roles[0] == 'student'){
/** Replace the standard loop with our custom loop */
remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'custom_student_loop' );
function custom_student_loop() {
$grades = array(); //Set up an empty array for the grades. We're gonna add grade categories as necessary based on user roles.
/** Check the roles of the current user, and add grade categories to the Grades array as needed */
$user = wp_get_current_user();
if ( in_array( 'grade_1_student', (array) $user->roles ) ) {
$grades[] = ('grade-1');
}
if ( in_array( 'grade_2_student', (array) $user->roles ) ) {
$grades[] = ('grade-2');
}
if ( in_array( 'grade_3_student', (array) $user->roles ) ) {
$grades[] = ('grade-3');
}
if ( in_array( 'grade_4_student', (array) $user->roles ) ) {
$grades[] = ('grade-4');
}
if ( in_array( 'grade_5_student', (array) $user->roles ) ) {
$grades[] = ('grade-5');
}
if ( in_array( 'grade_6_student', (array) $user->roles ) ) {
$grades[] = ('grade-6');
}
if ( in_array( 'grade_7_student', (array) $user->roles ) ) {
$grades[] = ('grade-7');
}
if ( in_array( 'grade_8_student', (array) $user->roles ) ) {
$grades[] = ('grade-8');
}
if ( in_array( 'grade_9_student', (array) $user->roles ) ) {
$grades[] = ('grade-9');
}
global $paged; // current paginated page
global $query_args; // grab the current wp_query() args
$args = array(
'paged' => $paged, // respect pagination
'tax_query' => array(
array(
'taxonomy' => 'homework-grades',
'field' => 'slug',
'terms' => $grades,
),
),
);
genesis_custom_loop( wp_parse_args($query_args, $args) );
}
}
Like I said, I'm sure there's a cleaner/better way to do this but I have not been able to find any examples to follow, and I've searched everything I can think of that would apply to this, but I don't know where else to look. If anyone can give me suggestions or point me in the right direction, that would be very much appreciated.
Thanks!
source https://stackoverflow.com/questions/71211054/conditionally-adding-items-to-an-array-with-if-statements
No comments:
Post a Comment