Wordpress usermeta from db returns null - php

Hi im trying to get some custom content from the database. I tryed in phpMyadmin:
SELECT DISTINCT meta_value FROM wp_usermeta WHERE meta_key = 'company'
Which returns the correct content.
Im now trying to get the content in my plugin. But its returning null
global $wpdb;
$companys = $wpdb->get_results("SELECT DISTINCT meta_value FROM wp_usermeta WHERE meta_key = 'company'");
var_dump($companys);
Im new to sql, and googled for hours, but with no result...

You just need to use DISTINCT to your SQL query, something like:
global $wpdb;
$companys = $wpdb->get_results("SELECT DISTINCT(meta_value) FROM $wpdb->usermeta WHERE meta_key = 'company'" );
var_dump($companys);

Related

Search from all custom-fields very slow. I need filter search for custom post type

I'm doing a custom search in my WP and in the search field, any typed word will be sought in custom-fields, in the titles and posting content.
It turns out that my database has more than 1 million custom-fields lines, and wanted to limit the search only for a certain type of post.
I already do this in the Loop to display the results, but I wish this filter was made in consultation because the page is taking over 20 seconds to display the result.
Can anyone help me? Below the code I'm using.
// SEARCH FROM ALL CUSTOM FIELDS
$post_ids_meta = $wpdb->get_col( $wpdb->prepare( "
ALTER TABLE wp_posts ADD INDEX (postmeta)
SELECT DISTINCT post_id FROM {$wpdb->postmeta}
WHERE meta_value LIKE '%s'
", $keyword ) );
// SEARCH FOR TITLE AND CONTENT
$post_ids_post = $wpdb->get_col( $wpdb->prepare( "
ALTER TABLE wp_post s ADD INDEX (posts);
SELECT DISTINCT ID FROM {$wpdb->posts}
WHERE post_title LIKE '%s'
OR post_content LIKE '%s'
", $keyword, $keyword ) );
$post_ids = array_merge( $post_ids_meta, $post_ids_post );
UPDATE:
Try this one. It's not tested but I'm sure it will work if you check and fix it a little bit:
// SEARCH IN title, content and meta_value
$post_ids = $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT ID FROM {$wpdb->posts} AS p,
LEFT JOIN {$wpdb->postmeta} AS m,
ON m.post_id = p.ID
WHERE p.post_type = '%s'
AND (
post_title LIKE '%%s%'
OR m.meta_value LIKE '%%s%'
OR post_content LIKE '%%s%')
", $post_type, $keyword, $keyword, $keyword) );
Note:
Assume you have taken input $post_type & $keyword. Eg: $post_type = "fairs";
I added % before and after %s to make sure it's widecard search.
In this case, I use DISTINCT because the joint table have repeated IDs. My apologies for the previous fault assumption on your first query that it was not needed.
Speed is not guaranteed, since you are doing a widecard search on post_content which is not indexed.
You should make sure the meta_value field is indexed for a little faster speed. If you meta don't store too much text in it.
GOOD LUCK!
ORIGINAL:
Firstly, let's clarify these:
Remove these 2 lines as it won't help (it make it worse due to repeated call):
ALTER TABLE wp_posts ADD INDEX (postmeta)
And
ALTER TABLE wp_posts ADD INDEX (posts);
ID is already distinct. So it won't help you do: SELECT DISTINCT ID
The final queries should look like these:
// SEARCH FROM ALL CUSTOM FIELDS
$post_ids_meta = $wpdb->get_col( $wpdb->prepare( "
SELECT post_id FROM {$wpdb->postmeta}
WHERE meta_value LIKE '%s'
", $keyword ) );
// SEARCH FOR TITLE AND CONTENT
$post_ids_post = $wpdb->get_col( $wpdb->prepare( "
SELECT ID FROM {$wpdb->posts}
WHERE post_title LIKE '%s'
OR post_content LIKE '%s' // Remove this will boost performance by 90% because post_content is not indexed
", $keyword, $keyword ) );
$post_ids = array_merge( $post_ids_meta, $post_ids_post );
What I recommend is to use this plugin: https://wordpress.org/plugins/search-everything/
Assuming that $keyword has no wildcards, you might try expressing this query as:
SELECT ID
FROM {$wpdb->posts}
WHERE post_title LIKE '%s'
UNION
SELECT ID
FROM {$wpdb->posts}
WHERE post_content LIKE '%s';
MySQL might figure out to use the indexes for this. The indexes that you want are:
create index wp_post_title_id on wp_post(post_title, id);
create index wp_post_content_id on wp_post(post_content, id);
This assumes that{$wpdb->posts} is really wp_post.

MySql query double WHERE clause

I currently have a query that checks whether a certain word is found in the array values.
$imploded = implode("','",$company_array);
$query = "SELECT *
FROM $wpdb->usermeta
WHERE meta_key='company'
AND meta_value IN ('".$imploded."')";
The $company_array contains different values.
I want to add another WHERE clause but don't know how.
It should check on the users role:
SELECT*
FROM $wpdb->usermeta
WHERE meta_key = 'wp_capabilities'
AND meta_value = 'subscriber'
Maybe some sort of join queries? I have no clue.
==== Sample data and expected output ====
This is my current query
$query = "SELECT *
FROM $wpdb->usermeta
WHERE meta_key='company'
AND meta_value IN ('".$imploded."')";
I want to add the following query
SELECT*
FROM $wpdb->usermeta
WHERE meta_key = 'wp_capabilities'
AND meta_value = 'subscriber'
The first query loads a list of users that work for a certain company.
The problem is................
Crap. I just realised something while writing this.
The problem was that the administrator is also listed in the list of users. I wanted him out of the results.
The users are listed based upon their value in the company field. But if that is empty the admin isn't listed anywhere.
Your WHERE clause needs to be
WHERE (meta_key='company' AND meta_value IN ('".$imploded."'))
OR (meta_key = 'wp_capabilities' AND meta_value = 'subscriber')
try like this
$query = "SELECT *
FROM $wpdb->usermeta
WHERE (meta_key='company'
AND meta_value IN ('".$imploded."')) or (meta_key = 'wp_capabilities' and meta_value = 'subscriber')";
I think you required below. Note the () with OR for your both where clauses.
$query = "SELECT *
FROM $wpdb->usermeta
WHERE ( meta_key='company' AND meta_value IN ('".$imploded."')")
OR (meta_key = 'wp_capabilities' AND meta_value = 'subscriber');

Custom SQL query with custom taxonomies (Wordpress)

I use the following SQL query to fetch custom posts in Wordpress.
I ended up with this solution because i needed to fetch und sort the posts based on custom meta data. This woks pretty well so far!
But how do i incorporate custom taxonomies in my query?
Say for example only fetch posts that are associated with term_id 5?
I'm really stuck here cause i can't figure out how wp_terms, relations etc are connected...
Any help is greatly appreciated!
UPDATE:
After some reading the solution in my case is this:
WordPress stores the relations between taxonomies and posts in wp_term_relationships (where object_id is the post_id and term_taxonomy_id ist the term_id in wp_terms). So if i want to only fetch posts that belong to a specific term_id, i came up with the following query. Seems to work as far as i can tell!
This is my query
global $wpdb;
$activelang = ICL_LANGUAGE_CODE;
$cmonth = date('Y-m');
$myquery = "
SELECT wposts.*, wpostmeta.meta_value AS date
FROM wp_posts wposts, wp_postmeta wpostmeta, wp_icl_translations wicl_translations, , wp_term_relationships wptermrelations
WHERE wposts.post_status = 'publish'
AND wpostmeta.post_id = wposts.ID
AND (wptermrelations.object_id = wposts.ID AND (wptermrelations.term_taxonomy_id = '29' OR wptermrelations.term_taxonomy_id = '30'))
AND wposts.post_type = 'event'
AND wicl_translations.element_id = wposts.ID
AND wicl_translations.language_code = '$activelang'
AND (wpostmeta.meta_key = '_ws_prem_date' OR wpostmeta.meta_key = '_ws_date1_date' OR ... ... OR wpostmeta.meta_key = '_ws_date10_date')
AND wpostmeta.meta_value >= '$cmonth-01'
ORDER BY CAST(date AS DATETIME),wposts.post_title ASC
";
$myloop = $wpdb->get_results($myquery);
In case someone is wondering what this query does:
This query fetches custom post types (events that have multiple dates associated) and builds a loop for these events that allows for duplicate entries since a 'normal' WordPress loop always filters out any duplicate entries.

How to join wp_posts and wp_postmeta in wordpress ecommerce plugin retrieving only product title, product description and price?

I'm using wp-ecommerce plugin for my own online ordering bakeshop (http://www.kingsbakery.mpkproducts.com/)
I don't want the way how customers made an order. I want similar order form like this (https://www.ssfamousdeli.com/order_ship.aspx).
I run a custom query in Mysql and I can only retrieve the product title and description. I use this sql statement:
<?php
$sql = "SELECT * FROM wp_posts WHERE
post_type like 'wpsc_product' AND
post_status like 'publish'
ORDER BY ID Asc";
$query = mysql_query($sql);
?>
I only stop there coz I don't know how to join wp_postmeta to select the price.
Please help. Thanks
<?php
$sql = "SELECT wp_p.*, wp_pm.meta_value FROM wp_posts wp_p, wp_postmeta wp_pm WHERE
wp_p.post_type like 'wpsc_product' AND
wp_p.post_status like 'publish' AND
wp_p.ID = wp_pm.post_id
wp_pm.key = 'Price' --This should be the meta key
ORDER BY wp_p.ID Asc";
$query = mysql_query($sql);
?>
Hope this will be of help.

How can I grab data from all of the matching fields?

What is the propper syntax to grab data from all of the matching fields?
This example outputs only 1 of the matching fields:
$myvariable = "SELECT post_content
FROM wp_posts
WHERE post_name = 'testing'
AND post_status = 'publish'
AND post_type = 'post'";
echo = $myvariable;
You need to fetch an array of that query:
<?php
$query = mysql_query("SELECT post_content FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'");
while($result = mysql_fetch_array($query)){
echo $result['post_content'];
}
?>
That will loop through the result list from the query and echo the post_content field value.
EDIT: Wow... Same thing, a few seconds late. Ha!
Your question is not clear to me. There may be two cases:
You want to get all the rows which match you condition.
then you should use a loop to grab all matching records as below:
$result = mysql_query("SELECT post_content FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'");
if(mysql_num_rows($result)>0)
while($row = mysql_fetch_assoc($result)){
echo $row['post_content'];
}
I couldn't understand what you want to know. If you want to select all the fields of selecting row then use:
SELECT * FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'
OR
SELECT col1,col2,...,coln FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'
If you want to check conditions with all the fields then you are on the right track, just compare each value with its respective column.
list all the fields in your select statement or use * to select all.
$myvariable = "SELECT * FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'"
You'll need to pull out the query and run a loop over the result rows that come back.
$query = mysql_query("SELECT post_content FROM wp_posts
WHERE post_name='testing'
AND post_status='publish' AND post_type = 'post'");
You'll need to adjust the above query to whichever rows you want to display as well as whatever criteria you want to match against.
And then run something like a while loop with each pass of the rows that were returned:
while($result = mysql_fetch_array($query))
{
echo $result["post_content"];
}
The above will go and pull out all the rows one by one that matched your query and display them however you style it.
If you want to match any, then your SQL is false.
SELECT post_content FROM wp_posts WHERE post_name = 'testing' OR post_status = 'publish' OR post_type = 'post'
The query above finds each record which contains exactly one of the search strings.
But if you want to find it within a sentence then you better use the MATCH function.
MySQL Full-Text Search Functions

Categories