Checking query results against exploded array - Wordpress, php - php

I have some brands listed against a user in the db which are input as a comma seperated list in the users profile - i get the individual brands associated to the user back by as follows
$brand_name = get_user_meta($user_id, 'brand', true);
$brands = explode(', ', $brand_name);
it works ok.
I am now creating brand pages which list their products, this is easy but i want to prevent users seeing the pages of the brands that they arent subscribed to.
my code that isnt working is below:
foreach ( $results as $result ){
$brand_name = get_user_meta($user_id, 'brand', true);
$brands = explode(', ', $brand_name);
if($brands = $result->brand) {
echo '<h2>Title: ' . $result->title . '</h2><br/>';
} else {
echo 'You can\'t view that brand';
}
}
I think i need to do some sort of nested foreach/for loop but not sure - Thanks in advance.

foreach ( $results as $result )
{
$brand_name = get_user_meta($user_id, 'brand', true);
$brands = explode(', ', $brand_name);
if(in_array($result->brand,$brands))
{
echo '<h2>Title: ' . $result->title . '</h2><br/>';
}
else
{
echo 'You can\'t view that brand';
}
}
use in_array()

Related

Group WP user query by custom meta value

I'm trying to query WP Users and group them by billing_state, a custom meta key/value but I'm getting some unexpected results where it gives me some empty options but also is only returning one result per billing_state.
Based on some research on SO it was suggested I query all users and then create a new array where I can set the state as the array key then the user object as the value.
Here is what I tried:
add_shortcode('pro_pro_users','pro_pro_users');
function pro_pro_users(){
global $wpdb;
$user_query = new WP_User_Query( array( 'fields' => 'all' ) );
$users = $user_query->get_results();
if (!empty($users)) {
$usersByState = array();
foreach ($users as $user) {
$usersByState[get_user_meta($user->ID, 'billing_state', true)] = $user;
}
foreach ($usersByState as $k => $v){
if(!empty($v)) {
echo '<li><h5>' . $k . '</h5>';
echo '<ul>';
foreach ($v as $user) {
echo '<li>' . get_user_meta($user->ID, 'first_name', true) . ' ' . get_user_meta($user->ID, 'last_name', true) . ' (' . $user->display_name . ')</li>';
}
echo '</ul>';
echo '</li>';
}
}
echo '</ul>';
} else {
echo 'No users found';
}
}
Here is what is happening (note the empty ones and only one per state although I know some of these have more than one
I've checked:
https://codex.wordpress.org/Class_Reference/WP_User_Query
https://codex.wordpress.org/Database_Description#Table:_wp_users
https://codex.wordpress.org/Function_Reference/get_users
https://wordpress.stackexchange.com/questions/105937/group-posts-by-meta-key
https://wordpress.stackexchange.com/questions/205427/group-posts-by-attachment-meta-key
https://usersinsights.com/wordpress-user-meta-query/
What comes to my attention is that the following code will "override" each billing-state with the last user found:
$usersByState = array();
foreach ($users as $user) {
$usersByState[get_user_meta($user->ID, 'billing_state', true)] = $user;
}
From what I understood is that you should rather go for:
$usersByState = array();
foreach ($users as $user) {
$billing_state = get_user_meta($user->ID, 'billing_state', true);
if ($billing_state)
$usersByState[$billing_state][] = $user;
}
So by doing this you would collect several users for different states. Moreover this should take care of empty "states" as you described. Not sure whether this fully solves your issue but it might be a starting point for refining your function.

Wordpress: Sort usermeta data when using get_user_meta()

I have defined $table_name_employee as a table in my plugin that has a bunch of user info in it. The ID field mirrors the field in wp_users
That being said, I have this code...
$SQLQuery="select * from {$table_name_employee}";
$wpdb->query($SQLQuery);
$results=$wpdb->get_results($SQLQuery,ARRAY_A);
foreach($results as $result)
{
$all_meta_for_user = get_user_meta( $result['ID'] );
$last_name = $all_meta_for_user['last_name'][0];
$first_name = $all_meta_for_user['first_name'][0];
$doc_training_responsibility_option.= "\t<option value='{$result['ID']}'>{$last_name}, {$first_name}</option>\n";
}
Later in my code I use $doc_training_responsibility_option to output the <option> inside the <select>.
It works as expected; however, the results are not sorted. I have tried several ways to add the data into an array instead of defining $doc_training_responsibility_option immediately. My intent was to sort the array by last name and then output that array to $doc_training_responsibility_option but I have failed on each attempt.
**** UPDATE ****
My attempt is below...
$SQLQuery="select * from {$table_name_employee}";
$wpdb->query($SQLQuery);
$results=$wpdb->get_results($SQLQuery,ARRAY_A);
$r=array(); $i=0;
foreach($results as $result)
{
$all_meta_for_user = get_user_meta( $result['ID'] );
$r[$i]['ID']=$result['ID'];
$r[$i]['last_name']=$all_meta_for_user['last_name'][0];
$r[$i]['first_name']=$all_meta_for_user['first_name'][0];
$i++;
}
// ************************************************
// NOT SURE WHAT TO DO HERE TO SORT $r BY last_name
// ************************************************
foreach ($r as $result)
{
$doc_training_responsibility_option.= "\t<option value='{$result['ID']}'>{$result['last_name']}, {$result['first_name']}</option>\n";
}
right now you are getting the user ID in this varible:
$result['ID']
Now you need to get all users from wp_usermeta and order by last name.
So you need to use get users to accomplish your task.
$u = get_users(array('blog_id' => $GLOBALS['blog_id'], 'meta_key' => 'last_name', 'orderby' => 'meta_value'));
foreach ($u as $user) {
$n = get_user_meta( $user->ID, 'last_name', true );
echo "<option>";
echo $n;
echo "</option>";
}
Based on #Mauro comment, I created the code below which worked.
// Create list of plugin users
$SQLQuery="select ID from {$table_name_employee}";
$wpdb->query($SQLQuery);
$results=$wpdb->get_results($SQLQuery,ARRAY_A);
foreach($results as $result)
{
$plugin_user[]=$result[ID];
}
// Get list of WP users (sorted)
$u = get_users(array('blog_id' => $GLOBALS['blog_id'], 'meta_key' => 'last_name', 'orderby' => 'meta_value'));
foreach ($u as $user)
{
// See if WP user is also a plugin user
if(in_array($user->ID,$plugin_user) )
{
$all_meta_for_user = get_user_meta( $user->ID );
$last_name=$all_meta_for_user['last_name'][0];
$first_name=$all_meta_for_user['first_name'][0];
$doc_training_responsibility_option.= "\t<option value='{$user->ID}'>{$last_name}, {$first_name}</option>\n";
}
}

php pdo category level access

i want category level access to users, i will give from admin side which categories users should access and which are not. Here i have trouble please help me, here is my code
In my database permission table there, in that userid and catids fields there so user if click on category function will see in permission table if user has permission are not then it will dipplay.
public function Grants($username)
{
$q = $this->db->prepare("select * from permissions where user = ?");
$q->bindParam(1, $username);
$q->execute();
$results = $q->fetchAll();
return $results;
}
category page
$check = new Access;
$data = $check->Grants($user);
foreach($data as $v)
{
if($v['catid'] == $_GET['p'])
{
foreach($nav as $list)
{
echo '' . '<li style="display:inline; padding:10px;">' . $list['catname'] . '</li>' . '';
}
}
else{
echo 'Access Denied'; }
}
if i had only one category in permission table it is working fine, if user had two or more catids not working.
Permission table example:
User>1 catid>1,2,3 array model giving problem how do i solve please help, if i place only one category it is working.
If your data is stored as I think it is from what you posted, it would look like this:
------------------------
| User | catid |
------------------------
1 1,2,3
Am I right? If that is the case. Then when you call this:
$check = new Access;
$data = $check->Grants($user);
Your $data variable would contain something like this:
1,2,3
and NOT an array as you think it would.
What you should do is use explode() to create that url:
$check = new Access;
$data = explode(',', $check->Grants($user));
Which, in turn; should give you an array like this:
Array (
[0] => 1,
[1] => 2,
[2] => 3,
)
Allowing you to iterate as you require.
EDIT
As per your comment, you need to access the catid array element. Provided you have the right php version, you could simple do this:
$check = new Access;
$data = explode(',', $check->Grants($user)[0]['catid']);
Or if that throws error, try this:
$check = new Access;
$cats = $check->Grants($user);
$data = explode(',', $cats[0]['catid']);
I have found simple solution for this.
$check = new Access;
$data = $check->Grants($user);
foreach($data as $result)
{
$str = $result['catid'];
$string = explode(',' , $str);
}
if(in_array($_GET['p'], $string))
{
foreach($nav as $list)
{
echo '' . '<li style="display:inline; padding:10px;">' . $list['catname'] . '</li>' . '';
}
}
else { echo "You dont have permission"; }

Outputting categories authors have written in as a class (WordPress)

OK, I have a very specific question that I hope someone can shed some light on.
I have a page that lists authors outputting using the following code
<?php
$display_admins = false;
$order_by = 'post_count'; // 'nicename', 'email', 'url', 'registered', 'display_name', or 'post_count'
$role = ''; // 'subscriber', 'contributor', 'editor', 'author' - leave blank for 'all'
$hide_empty = true; // hides authors with zero posts
if(!empty($display_admins)) {
$blogusers = get_users('orderby='.$order_by.'&role='.$role);
} else {
$admins = get_users('role=administrator');
$exclude = array();
foreach($admins as $ad) {
$exclude[] = $ad->ID;
}
$exclude = implode(',', $exclude);
$blogusers = get_users('exclude='.$exclude.'&orderby='.$order_by.'&role='.$role.'&order='.'DESC');
}
$authors = array();
foreach ($blogusers as $bloguser) {
$user = get_userdata($bloguser->ID);
if(!empty($hide_empty)) {
$numposts = count_user_posts($user->ID);
if($numposts < 1) continue;
}
$authors[] = (array) $user;
}
echo '<ul class="contributors">';
foreach($authors as $author) {
$display_name = $author['data']->display_name;
$avatar = get_wp_user_avatar($author['ID'], 'medium');
$author_profile_url = get_author_posts_url($author['ID']);
$filter = get_userdata($author['ID'])->yim;
echo '<li><div class="home ', $filter,' "><div class="feature-image">', $avatar , '</div>
<div class="post-title"><h3>', $display_name, '</h3></div>
</div>
</li>';
}
echo '</ul>';
?>
(I got this from another support topic and tweaked it, although I can't remember where)
At the moment, the $filter variable is just a string I enter in the 'Yahoo IM' profile box (a dirty fix to test the filter). I'd like this to actually be a list of the categories (as slugs that I will output in to the class="" part of the loop) that the author has posted in.
I essentially want to be able to filter the authors by category that they have posted in, and the filter I'm using (Isotope) operates using the class, so outputting the categories in to the class of the markup is what I'm after.
Any suggestions gratefully received!
// Returns the posts made by the author
$authorPosts = get_posts("author={$author['ID']}");
$categoryList = array(); // reset previous values
foreach ($authorPosts as $post) {
$postCategories = get_the_category($post->ID);
// Add to the categories the author has posted in
foreach ($postCategories as $category)
$categoryList[] = $category->slug;
}
// Removes duplicate categories
$categoryList = array_unique($categoryList);
You can then use $filter = implode(' ', $categoryList); and add it to your html.
RE not storing the array from the other answer, you can just echo out the slugs there and then like this:
$authorPosts = get_posts("author={$author['ID']}");
foreach ($authorPosts as $post) {
$postCategories = get_the_category($post->ID);
// Add to the categories the author has posted in
foreach ($postCategories as $category)
echo($category->slug);
}
otherwise if you want to put your PHP at the top and echo out the slugs further down the page pop there where ever you want to echo them:
$i = 0;
foreach($categoryList as $category) {
echo($categoryList[$i]);
$i++;
}

Change a PHP array into separate strings

I have an array returned from sql and I need to get them into separate strings to use on the page. It is out of a single row in the database and lists all the folders a user has.
example in database john has a red folder, green folder, blue folder.
I run the query and use fetchAll to return john's folders. I have it in an array. I can echo the array and it outputs redfoldergreenfolderbluefolder
How can I take the array and split it into separate strings?
PHP code
$query = "SELECT album_name FROM albums WHERE username = :username";
$query_params = array(
':username' => $email
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
echo 'Database Error, please try again.';
}
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$post = array();
$post["album_name"] = $row["album_name"];
echo $post["album_name"]; // This just lists all albums together no spaces or commas
}
$text = implode(",", $post);
echo $text; // This just outputs the last item (bluefolder)
The below needs correction :
foreach ($rows as $row) {
$post = array();
$post["album_name"] = $row["album_name"];
echo $post["album_name"]; // This just lists all albums together no spaces or commas
}
$text = implode(",", $post);
echo $text; // This just outputs the last item (bluefolder)
Change the above to :
$post = array();
foreach( $rows as $row )
{
// $post = array(); // This line should not be here . It should be outside and above foreach
// The below echo is for test purpose . Comment it if you don't need it
echo $row["album_name"] ,' ';
// $post["album_name"] = $row["album_name"]; // This keeps assigning $row["album_name"] to same index "album_name" of $post . Eventually you will have only one value in $post
$post[] = $row["album_name"];
}
// $text = implode(",", $post); // With coma's as separator
$text = implode(" ", $post); // With blank's as separator
echo 'John has ' , $text;
try print_r($post); on your last line.
please use print_r($text) in side the for each and then you will get all the arry with commos
and remove $post = arry from there and put above of foreach.
i am trying to help you,may this help
thanks
anand
Try this:
$post = array();
foreach ($rows as $row) {
array_push($post, 'album_name', $row["album_name"]);
}
$text = implode(",", $post);
echo $text;
No assoc ver:
$post = array();
foreach ($rows as $row) {
$post[] = $row["album_name"];
}
$text = implode(",", $post);
echo $text;
The reason why it only show the last folder is because you do "$post = array()" at the beginning of your loop. It reset the array everytime... just take it out of the loop and put it above the foreach.
1: http://php.net/manual/en/function.imThe reason why it only show the last folder is because you do "$post = array()" at the beginning of your loop. It reset the array everytime... just take it out of the loop and put it above the foreach.
EDIT:
Try it this way :
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$post = array();
foreach ($rows as $key => $folder) {
array_push($post, $folder)
}
$text = implode(",", $post);

Categories