Without using WordPress or writing a plugin based on WordPress, I want to be able to fetch data from WordPress database tables and also insert into it. I will be writing the the code in either procedural or OOP but it’s definitely outside of the WordPress framework.
Right now, I am able to fetch from wp_users
table but trying to join wp_users
with wp_usermeta
is not working right. I wanted to display data relating to a particular user in the usermeta table but fetching is a bit difficuly since wp_usermeta
table uses meta_key
and meta_value
to save these data. So, how do you fetch first_name and last_name for a user when table columns are meta_key and meta_value?
I have tried using INNER JOIN but the result is not right. I might just have one particular user on two pages (table pagination) before the next user.
I would like every user’s data to be on the same row which will also help for updating later.
2
Answers
Assuming you have a user ID and you want to retrieve the first_name and last_name for that user, you can use a query like the following:
Note: Replace ‘:user_id’ with the actual user ID you want to fetch data for. Also, ensure that you have the correct table prefix in your queries, as it may vary based on your WordPress installation.
To fetch
first_name
andlast_name
for a user from the WordPress database tableswp_users
andwp_usermeta
, you need to perform a SQL query that joins these tables correctly. Since thewp_usermeta
table stores user metadata usingmeta_key
andmeta_value
columns, you’ll need to use a conditional join to fetch the specificmeta_value
forfirst_name
andlast_name
related to a particular user.Here’s an example of how you can achieve this:
Explanation:
We start with the
wp_users
table (u
) and use a LEFT JOIN to connect it with thewp_usermeta
table (um1
) using theuser_id
as the common field.In the SELECT statement, we use conditional aggregation (MAX with CASE statements) to fetch the
meta_value
forfirst_name
andlast_name
based on themeta_key
.We use a WHERE clause to filter the rows in
wp_usermeta
wheremeta_key
is either ‘first_name’ or ‘last_name’.Finally, we GROUP BY
ID
anduser_login
from thewp_users
table to ensure that each user’s data is on the same row.This query will return a result set with one row for each user, with their
first_name
andlast_name
displayed as separate columns.You can use this SQL query within your PHP code (either procedural or OOP) to fetch the data from the WordPress database without relying on the WordPress framework.