I have made a code for to filter wich pages to show depending on your user_role. Everything was alright. But my customer created NEW roles with similars name/slug.
So now, if some 1 have the role for exemple : Group APTNB, he will be able to see pages with role APTNB_CA because in the slug 'aptnb' is LIKE 'aptnb_ca' in my comparaison.
I have try to explore the possibility to use 'IN' with this post : Meta_query compare operator explanation
My script juste exploded when I used it.
Here is my code.
global $current_user;
$user_roles = $current_user->roles;
$user_role_query = array();
for ($i=0; $i < sizeof($user_roles); $i++) {
$user_role_query[] = array(
'key'=>'attribution_roles',
'value' => $user_roles[$i],
'compare'=>'LIKE'
);
}
// WP_Query arguments
$args = array (
'post_type' => 'suivi_des_comites',
'order' => 'ASC',
'orderby' => 'title',
'posts_per_page' => -1,
'meta_query' => array_merge(
array( 'relation' => 'OR' ), // this must be an array
$user_role_query
)
);
The key, I think would be to rework the array()'s to make it work.
Here some of my print_r();
print_r($user_role_query);
Array
(
[0] => Array
(
[key] => attribution_roles
[value] => aptnb
[compare] => LIKE
)
)
print_r($args);
Array
(
[post_type] => suivi_des_comites
[order] => ASC
[orderby] => title
[posts_per_page] => -1
[meta_query] => Array
(
[relation] => OR
[0] => Array
(
[key] => attribution_roles
[value] => aptnb
[compare] => LIKE
)
)
)
In my DB, the page attribute "attribution_roles" return this.
a:2:{i:0;s:8:"aptnb_ca";i:1;s:13:"administrator";}
When I use the method LIKE
my query looks like this.
SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND (( wp_postmeta.meta_key = 'attribution_roles' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%administrator%' )) AND wp_posts.post_type = 'suivi_des_comites' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_title ASC
When I use the method =
my query looks like this.
SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( ( wp_postmeta.meta_key = 'attribution_roles' AND CAST(wp_postmeta.meta_value AS CHAR) = 'administrator' ) ) AND wp_posts.post_type = 'suivi_des_comites' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_title ASC
My objective is to fix the issue that [value] => aptnb is the same as [value] => aptnb_ca
and my query would looks like : FIND all post with custom post_type suivi_des_comites where user_role == 'aptnb_ca' OR user_role == 'aptnb'
It needs to be the exact string and not a part of it.