How to get a single variable in Wordpress - php

I am running a competition which is based on WP Custom Fields. I am trying to count all meta values of a meta_key='odd' for a specific user. I am using the formula below but it's not returning any result.
$meta_key = 'odd';
$post_author = 'Admin';
$odd = $wpdb->get_var( $wpdb->prepare(
"
SELECT Count(meta_value)
FROM $wpdb->postmeta
INNER JOIN $wpdb->posts ON $wpdb->postmeta->post_id = $wpdb->posts->ID
WHERE $wpdb->postmeta->meta_key = 'odd' AND $wpdb->posts->post_author = 'Admin'
",
$meta_key, $post_author
) );
echo "<p>Total odd {$odd}</p>";
Anyone can help me? Thanks in advance.

You are mixing up the $wpdb variables and the $post variables - for your JOIN, for example, you can't use $wpdb->postmeta->post_id, it would be {$wpdb->postmeta}.post_id, and would be even better to just use table aliases. Your prepare() is also not passing in your meta_key or author because you don't have %s placeholders for them
$odd = $wpdb->get_var( $wpdb->prepare(
"
SELECT count(meta_value)
FROM {$wpdb->postmeta} pm
INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
WHERE pm.meta_key = %s AND p.post_author = %s
",
$meta_key, $post_author
) );

Related

How can I combine two SQL queries using INNER JOIN?

I have 2 SQL queries as below:
$results2 = $wpdb->get_results("SELECT * FROM `wp_posts` WHERE id IN (".implode(",", $product_ids).")");
$getprice = $wpdb->get_results("SELECT * FROM `wp_postmeta` WHERE meta_key='_regular_price' AND post_id IN (".implode(",", $product_ids).")");
I have combined them as below query:
$yeni = $wpdb->get_results("SELECT wp_posts.id, wp_posts.post_title, wp_postmeta.meta_value
FROM wp_posts
INNER JOIN wp_postmeta ON wp_posts.id = wp_postmeta.post_id
WHERE meta_key = '_regular_price'
WHERE wp_posts.id IN (".implode(",", $product_ids).")");
After combining the queries, it's giving an empty result. I can't find the issue with the updated query.
Try this sql.
I have replace this WHERE meta_key = '_regular_price'
$yeni = $wpdb->get_results("SELECT wp_posts.id, wp_posts.post_title, wp_postmeta.meta_value FROM wp_posts INNER JOIN wp_postmeta ON wp_posts.id = wp_postmeta.post_id WHERE wp_posts.id IN (".implode(",", $product_ids).") and wp_postmeta.meta_key = '_regular_price'");
I don't understand why you don't use the native Wordpress features via OOP procedure.
Your simple query, it can be translated like this:
<?php
$loop = new WP_Query(
array(
'post_type' => 'page', // post type: page, post, attachment etc..
'post__in' => $productIds, // array[]
)
);
// after that, you can use a standard wordpress loop
if($loop->have_posts()) {
while($loop->have_posts()) {
: $loop->the_post();
the_title();
print "<br>";
// access to meta key _regular_price
print get_post_meta(get_the_ID(), '_regular_price', true);
}
}
This is the right way.
Cheers
Class reference here: https://developer.wordpress.org/reference/classes/wp_query/

Is it possible to filter results by a specific meta key's value?

I'm trying to show the total value for all orders in certain status whose payment method is "ppec-paypal".
I've tried using the AND function to filter by meta.meta_value
add_shortcode( 'show_total_pp', 'show_total_pp_shortcode' );
function show_total_pp_shortcode() {
global $wpdb;
$order_totalpp = apply_filters( 'woocommerce_reports_sales_overview_order_totals', $wpdb->get_row( "
SELECT SUM(meta.meta_value) AS total_sales, COUNT(posts.ID) AS total_orders FROM {$wpdb->posts} AS posts
LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id
WHERE meta.meta_key = '_order_total'
AND posts.post_type = 'shop_order'
AND meta.meta_value = 'ppec_paypal'
AND posts.post_status IN ( '" . implode( "','", array( 'wc-processing','wc-on-hold' ) ) . "' )
" ) );
return absint( $order_totalpp->total_sales);
echo $order_totalpp;
}
I have this code string working for orders based on just the status's, but when I try to filter the payment method by adding the line:
" AND meta.meta_value _payment_method = 'ppec_paypal' "
it does not work, gets a '0' value.
I'm guessing there is syntax error in my code.
for a left join you should not use column related to the left joined table in where clause (this way work as an inner join)
but you should add this condition to the related ON clause
SELECT SUM(meta.meta_value) AS total_sales, COUNT(posts.ID) AS total_orders
FROM {$wpdb->posts} AS posts
LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id
AND meta.meta_key = '_order_total'
AND meta.meta_value = 'ppec_paypal'
WHERE posts.post_type = 'shop_order'
AND posts.post_status IN ( '" . implode( "','", array( 'wc-processing','wc-on-hold' ) ) . "' )

Get products IDs by _sale_price_dates_to before now in Woocommerce

I try to get the post_ids from postmeta where the _sale_price_dates_to are less the now. And I did something like this:
global $wpdb;
$publishid = $wpdb->get_results('SELECT meta_value FROM ' . $wpdb->postmeta . ' WHERE meta_key="_sale_price_dates_to" and meta_value<=' .time().'') or die("Error: Cannot create object");
But it doesn't work. Maybe because the _sale_price_dates_to has format longtext not date. how to change it in the query?
But It's not over. I want to add the condition that the products have to be published then I have to join:
$publishid = $wpdb->get_results('SELECT meta_value FROM ' . $wpdb->postmeta . 'join' . $wpdb->posts . ' ON wp_posts.ID = wp_postmeta.post_id WHERE wp_postmeta.meta_key="_sale_price_dates_to" and wp_postmeta.meta_value<=' .time().' and wp_posts.post_status="publish" ') or die("Error: Cannot create object");
But because of the first problem, I don't know it works.
Update: Setting up the right time zone in the code
Try the following to make a functional SQL query using WPDB to get the Post IDs where post meta _sale_price_dates_to timestamp is less the now time stamp:
global $wpdb;
// Set the correct time zone (http://php.net/manual/en/timezones.php)
date_default_timezone_set('Europe/Paris');
// An array of IDs
$results = $wpdb->get_col("
SELECT p.ID
FROM {$wpdb->prefix}posts AS p
JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
WHERE p.post_status = 'publish'
AND pm.meta_key = '_sale_price_dates_to'
AND pm.meta_value <= '".time()."'
AND pm.meta_value != ''
");
// Raw Output (array of post IDs)
print_r($results);
Tested and works.
meta_value != '' is needed to avoid Post IDs with empty values to be queried.

PHP / mySQL - Query to Retrieve Only Unique Meta Values

I need help in rewriting the query below to accept a second and a second + third qualification.
Example meta keys and values:
Trees
meta_key = trees
meta_value = pine, oak, sequoia
States
meta_key = states
meta_value = california, washington, florida
Countries
meta_key = countries
meta_value = usa, uk, ireland
I attempted to add these AND statements but I was not able to cause it to work properly.
Second qualification:
AND (pm.meta_key = 'states' AND pm.meta_value = 'california')
Second and third qualification:
AND (pm.meta_key = 'states' AND pm.meta_value = 'california')
AND (pm.meta_key = 'countires' AND pm.meta_value = 'usa')
Function with query I need help in rewritting:
function get_unique_post_meta_values( $key = 'trees', $type = 'post', $status = 'publish' ) {
global $wpdb;
if( empty( $key ) )
return;
$res = $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
return $res;
}
Thanks in advance for your help! Please let me know if further clarification is required.
If the function sets $key=trees, what is the point of an empty check? Additionally, I think you are missing the curly brackets. You are selecting 'pm.meta_value', which is why are you doing a LEFT JOIN, I think? Maybe seeing your DB structure would help me understand that, but an INNER JOIN is what you want.
if( empty( $key ) ){
return;
} else {
$res = $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm
INNER JOIN {$wpdb->posts} as p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
return $res;
}
Try this. If it doesn't work then update this question with more details and I will help guide you further.

Wordpress Custom Query Against Taxonomy Term and Post Metadata

I have this custom query I need to do that will check against both post_metadata values and taxonomy terms. I'm using code that I modified from Wordpress's codex, but it is returning zero results consistently. Is there a mistake I've made? (UPDATED: shows where it is being loaded into a variable first)
global $wpdb;
$querystr = "
SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->terms.name = '" . $service . "'
AND $wpdb->term_taxonomy.taxonomy = 'Services'
AND $wpdb->postmeta.meta_value = '" . $county . "'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->postmeta.meta_key = 'order'
ORDER BY $wpdb->postmeta.meta_value ASC";
$pageposts = $wpdb->get_results($querystr, OBJECT);
I would suggest logging the actual string that is executed (save this select to a variable and log the variable, then pass the variable to the wpdb query). Once you have the sql, you can more easily troubleshoot it (or post it here for further assistance).

Categories