I am trying to query databse to get posts with meta_key
equals meta_value
but it returns empty array, while if i used get_posts
i got required result, what is wrong with my code (I hooked it to footer to check)
global $wpdb;
$wpdb->show_errors( true );
$querystr = "
SELECT $wpdb->posts.*
FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
WHERE $wpdb->postmeta.meta_key = 'workshop_id'
AND $wpdb->postmeta.meta_value = '13465'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'forum'
ORDER BY $wpdb->posts.ID ASC
";
$workshops = $wpdb->get_results($querystr, OBJECT);
print_r($workshops);
Using this:
$workshops = get_posts([
'post_type' => 'forum',
'numberposts' => -1,
'post_status' => 'publish',
'meta_key' => 'workshop_id',
'meta_value' => '13465',
]);
print_r($workshops);
i get:
Array
(
[0] => WP_Post Object
(
[ID] => 13562
[post_author] => 1
[post_date] => 2019-01-02 20:05:21
[post_date_gmt] => 2019-01-02 17:05:21
//And the rest of properties..
)
)
Update
I have tried the following query and it worked(Why the one with problem doesn't):
$workshops_query = $wpdb->get_results(
$wpdb->prepare(
"
SELECT post_id FROM $wpdb->postmeta
WHERE meta_key = %s
AND meta_value = %s
",
'workshop_id', '13465'
)
, OBJECT);
foreach($workshops_query as $workshop_query){
$workshops[] = $workshop_query->post_id;
}
And yes both of queries tends to return different results, but one of them works, why the other doesn't?