Get user id from wp_usermeta table - php

I have stored the certain term ids in wp_usermeta table.
i want to get the user id where the term id match with the user meta key 'location' value.
i have tried it with below query but it is doing nothing.
global $wpdb;
$term = get_queried_object();
$query = $wpdb->get_results("SELECT user_id FROM wp_usermeta WHERE meta_key='location' AND meta_value LIKE %s",'%'.$term->term_id.'%');

try this, you are not passing the value correctly
$query = $wpdb->get_results("SELECT user_id FROM wp_usermeta WHERE
meta_key='location' AND meta_value LIKE '%s,%".$term->term_id."%'");

Is there any reason for using a sql query? i think this will do what you want exactly :
$user_query = new WP_User_Query( array( 'meta_key' => 'location', 'meta_value' => 'ANY' ) );
foreach ($user_query as $user) {
$user->ID; // the the user id
}

I have figured it out. Here is my solution. if someone needed.
$term = get_queried_object();
$wpdb->get_results($wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key='location' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $term->term_id . '%'));

Related

Getting a single MYSQL result where the field is an array

Wordpress database, bit stuck on this one.
I'm using the following to get the ID of the current user.
$user_ID = get_current_user_id();
This returns something like this :
15
Now I try to find the matching value of $user_ID in the field show_user_list The data in this field is stored in an array.
Which looks something like this :
a:2:{i:0;s:2:"29";i:1;s:2:"15";}
This is the query i'm running (along with a set of conditions) :
global $wpdb; $result = $wpdb->get_results( "SELECT post_id FROM wp_postmeta WHERE show_user_list IN (' . implode(',', $user_ID) . ' AND post_type = 'show' AND post_status = 'publish'" );
And then I'm trying to echo the value of the matching post_id with this :
foreach ( $result as $unique ) {
echo $unique->post_id;
}
But it's not returning anything. I know I must be making a mistake while dealing with the array but I don't know where I'm going wrong?
looks like you have stored a serialized array in the show_user_list field, so it will be a hustle to search for values into using a db query.
In the model you described, you have to select all the rows from wp_postmeta that match "post_type = 'show' AND post_status = 'publish'", then manually filter results that do not have the user id in the unserialized show_user_list field.
You might try something like :
in_array($user_ID, unserialize($row->show_user_list))
Also, I noticed multiple errors in your query: string not properly concatenated with PHP code and the right parenthesis of the IN clause not closed.
Regards,
same
EDIT
Here is how I would solve your problem providing info you have given :
$user_ID = get_current_user_id();
global $wpdb;
$results = $wpdb->get_results("SELECT post_id, show_user_list FROM wp_postmeta WHERE post_type = 'show' AND post_status = 'publish'");
$user_post_ids = array();
foreach ($results as $post) {
if (in_array($user_ID, unserialize($post->show_user_list))) {
$user_post_ids[] = $post->post_id;
}
}
Hope this helps !

How to see if a post exists based on a meta value

Is there any way to see if a post exists by a meta value?
For instance, lets say I want to see if another post has a unique meta value of "pictureID", and if so do something else.
Is there a way I could write that clause in php?
Thank you
if you dont know the post id then
you can use custom wordpress query to check post meta according to key like
global $wpdb;
$wpdb->get_results( "select * from $wpdb->postmeta where meta_key = 'pictureID' " );
And then you can get all results with post id and then get that post data.
Hope this helps ;)
You can use a standard WP_Query to return posts by meta_key using the meta_query argument and EXISTS compare type.
// query for all posts with the pictureID meta key set
$args = array(
'post_type' => 'post', // or your_custom_post_type
'meta_query' => array(
array(
'key' => 'pictureID',
'compare' => 'EXISTS',
),
),
}
// create a custom query
$my_query = new WP_Query( $args );
// loop over your query, creating a custom The Loop
if ( $my_query->have_posts() ): while ( $my_query->have_posts() ): $my_query->the_post();
// $post is now posts that have a pictureId meta value
endwhile; endif;
// reset $post
wp_reset_postdata();
If you want to quickly grab a random post_id that has this meta_key set you can go to the database directly (bypassing caching, etc).
global $wpdb;
// SQL statement to fetch the post_id using a meta_key and a published post
$sql = <<<SQL
SELECT post_id
FROM {$wpdb->postmeta} pm
JOIN {$wpdb->posts} p
ON p.ID = pm.post_id
AND post_status = 'publish'
AND post_type = 'post'
WHERE meta_key = 'pictureID'
AND meta_value != ''
AND post_id != %d
ORDER BY RAND()
LIMIT 1
SQL;
// exclude the current post by replacing %d with the current ID
$sql = $wpdb->prepare( $sql, $post->ID );
// use get_var() to return the post_id
$post_id = $wpdb->get_var( $sql );
first try to get meta value for post get_post_meta()
$postMetaValue=get_post_meta($postId,"meta_key",true);
if($postMetaValue=='pictureID')
{
//do as you want
}

Wordpress - $query, how to order users by lastname

I am trying to change a query that gets users from the db and orders by user_nicename. I would like to sort the order of the users by surname. I have tried changing the ORDER BY the meta data value of last_name, but this didn't work.
Here is the current bit of code that I am trying to change:
global $wpdb;
$query = "SELECT ID, user_nicename from $wpdb->users ORDER BY user_nicename";
$author_ids = $wpdb->get_results($query);
Any tips or help would be greatly appreciated. I am new to PHP and and learning, but have found myself stumped by this problem.
Many thanks
This will enable you to retrieve users orderby their lastname.
$args = array(
'meta_key' => 'last_name',
);
$wp_user_query = new WP_User_Query($args);
$wp_user_query->query_orderby = str_replace( 'user_login', 'wp_usermeta.meta_value', $wp_user_query->query_orderby );
$wp_user_query->query();
$users = $wp_user_query->get_results();

WordPress custom SQL

I have this function which contains some custom SQL:
function user_comment_count_by_meta( $user_id, $meta_key )
{
global $wpdb;
$count = 0;
$sql = "SELECT count(*) FROM $wpdb->comments comments INNER JOIN $wpdb->commentmeta meta ON comments.comment_ID = meta.comment_id WHERE comments.user_id = %d AND meta.meta_key = %s";
$count = $wpdb->get_var( $wpdb->prepare( $sql, $user_id, $meta_key ) );
return $count;
}
What it should be doing is counting all the comments for a user that have a particular meta value attached to them and returning that number. So for example if a user has made 20 comments and then 11 of those have the meta value 'accepted' attached to them then the number returned would be 11.
I call the function like so:
<?php $count = user_comment_count_by_meta( get_the_author_meta('id'), 'accepted' ); ?>
However it doesn't return anything. Not sure where I have gone wrong? If any SQL geniuses could help or if anyone can spot a problem it'd be much appreciated. Thanks.
Well,I think that the SQL it's ok, but when you call your function you are using
get_the_author_meta('id')
and this function I think that have other meaning.
If you want the ID from the post author you must use:
get_the_author_ID()
I'm not sure. really.

Ordering Wordpress posts by most recent comment

I'm wanting to order Wordpress posts by the most recent comment. To the best of my knowledge this isn't possible using the WP_Query object, and would require a custom $wpdb query, which I can easily write. However, I then don't know how to setup the loop to run off this object.
Can anyone help?
Assign
select wp_posts.*, max(comment_date) as max_comment_date
from $wpdb->posts wp_posts
right join $wpdb->comments
on id = comment_post_id
group by ID
order by max_comment_date desc
limit 10
to some variable $query. You can fiddle around with the 10 or the query itself. (I'm no SQL optimization ninja.) Then your code will look something like
<?php
$results = $wpdb->get_results($query) or die('!');
foreach ($results as $result):
?>
[insert template here]
<?php endforeach ?>
This pattern is covered in more depth by the Codex.
I used a simpler, portion of a native WP in function. hope it helps and some one can continue to develop. Here is a simplified version that shows the title & excerpt of the post along with the comment content & author from the latest commented posts using get_comments.
$args = array(
'status' => 'approve',
'number' => 6,
'order' => 'DESC'
);
$comments = get_comments($args);
foreach($comments as $comment) : $count++;
$post_args = array(
'post_type' => 'post',
'p' => $comment->comment_post_ID,
'posts_per_page' => 1
);
$posts = get_posts($post_args);
foreach($posts as $post) : setup_postdata($post);
the_title();
the_excerpt();
endforeach;
echo $comment->comment_content;
echo $comment->comment_author;
endforeach;
OK guys,
A lot of great answers here, but obviously nobody's taken the time to test them.
Hao Lian gets the credit for the first best original answer, but unfortunately his code doesn't show posts without comments.
Captain Keytar is on the right track, but his code will display every single post and attachment as a separate result.
Here is a modified version of Captain Keytar but it limits the results to the type 'post'.. that has been published (to avoid getting drafts!!)
select wp_posts.*,
coalesce(
(
select max(comment_date)
from $wpdb->comments wpc
where wpc.comment_post_id = wp_posts.id
),
wp_posts.post_date
) as mcomment_date
from $wpdb->posts wp_posts
where post_type = 'post'
and post_status = 'publish'
order by mcomment_date desc
limit 10
This is an old question, but I had the same issue and found a much cleaner way to do this, so I'm posting it here in case it helps anyone.
If you use the posts_clauses filter you can then just modify the main query and still use The Loop and all the regular loop functions.
function intercept_query_clauses( $pieces ) {
global $wpdb;
$pieces['fields'] = "wp_posts.*,
(
select max(comment_date)
from " . $wpdb->comments ." wpc
where wpc.comment_post_id = wp_posts.id AND wpc.comment_approved = 1
) as mcomment_date";
$pieces['orderby'] = "mcomment_date desc";
return $pieces;
}
add_filter( 'posts_clauses', 'intercept_query_clauses', 20, 1 );
Note that I changed the sql slightly for my own purposes, but the general concept is the same.
As an addendum to Hao Lian's answer, if you use the following query:
select wp_posts.*,
coalesce(
(
select max(comment_date)
from $wpdb->comments wpc
where wpc.comment_post_id = wp_posts.id
),
wp_posts.post_date
) as mcomment_date
from $wpdb->posts wp_posts
order by mcomment_date desc
limit 10
This mixes in posts that don't have comments yet, and sorts them by post_date and max(comment_date).
Code suggested by Hao Lian works perfect except for the fact that we should add the following WHERE clause to avoid pulling POST with comment_count = 0, this situation is caused by spam comments.
The WHERE clause to add is as follows:
WHERE comment_approved = '1' AND comment_type = '' AND post_password = ''
Complete code after adding the where clause shoud look like following:
select wp_posts.*, max(comment_date) as comment_date
from wp_posts
right join wp_comments on id = comment_post_id
WHERE comment_approved = '1' AND comment_type = '' AND post_password = ''
group by ID
order by comment_date desc
limit 6
This can be done by combining WP_Comment_Query with WP_Query, like this:
// For performance, limit the number of queried comments,
// but make it be something big enough to account for "duplicate" posts.
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( array( 'number' => '100' ) );
if ( $comments ) {
foreach ( $comments as $comment ) {
// You'll want to convert the dates from string to integer so you can sort them out later
$comment_utf = strtotime($comment->comment_date);
// Build an array of post IDs with the date of the last published comment
$latest_comments[$comment->comment_post_ID] = $comment_utf;
}}
// Sort the array by date
arsort($latest_comments); foreach ($latest_comments as $key => $value) { $posts_ordered[] = $key; }
// The nice thing is that WP_Query will remove duplicates by default
$args = array ( 'posts_per_page' => '10', 'post__in' => $posts_ordered, 'orderby' => 'post__in');
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Do your stuff (add the template or whatever)
// If you want to add the comment itself, use this:
$comments = get_comments(array('number' => '1', 'post_id' => $post->ID));
foreach($comments as $comment) :
echo $comment->comment_content;
endforeach;
// That's about it
}}
wp_reset_postdata();
I'm thinking that adding in the max function will screw up your results. MySQL isn't going to pull the max from each one. It's going to pull the max from the full set. This is the query that'll get you your results:
select wp_posts.*, comment_date
from $wpdb->posts wp_posts
right join $wpdb->comments
on id = comment_post_id
group by ID
order by comment_date desc
limit 10
After that, if you want to follow WP convention, use this, and then you can use the functions that most of your templates are using (based on the loop):
$results = $wpdb->get_results($query) or die('!');
foreach ($results as $post):
setup_postdata($post);
Get 3 newest comments for custom post type 'question' regardless of approvement:
global $wpdb;
$results = $wpdb->get_results(
"
SELECT wp_posts.ID, MAX(comment_date) AS max_comment_date
FROM wp_posts
RIGHT JOIN wp_comments
ON id = comment_post_id
WHERE wp_posts.post_type = 'question'
AND wp_posts.post_status = 'publish'
GROUP BY ID
ORDER BY max_comment_date DESC
LIMIT 3
"
);
foreach ($results as $result) {
$posts_arr[] = $result->ID;
}
$args = array(
'post_type' => 'question',
'post__in' => $posts_arr,
'orderby' => 'post__in',
);
$the_query = new WP_Query( $args );
Using Lucian's BEAUTIFUL solution, I needed to alter/filter the existing WP_Query to sort posts by the latest comment. Here's the code, tested & works perfectly:
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( array( 'number' => '100' ) );
if ( $comments ) {
foreach ( $comments as $comment ) {
$comment_utf = strtotime($comment->comment_date);
$latest_comments[$comment->comment_post_ID] = $comment_utf;
}
// Sort the array by date
arsort( $latest_comments );
foreach( $latest_comments as $key => $value ) {
$posts_ordered[] = $key;
}
$query->set( 'post__in', $posts_ordered );
$query->set( 'orderby', 'post__in' );
}

Categories