Age-old question(#1, #2), I still am struggling with the issue. Now trying with a simple SQL Query:
global $wpbd;
$post_table = $wpdb->prefix . 'posts';
$meta_table = $wpdb->prefix . 'postmeta';
$fs_query = "SELECT $post_table.ID
FROM $post_table
INNER JOIN $meta_table
ON ( $post_table.ID = $meta_table.post_id )
WHERE 1=1
AND $post_table.post_type = 'services'
AND $post_table.post_status = 'publish'
AND (
$meta_table.meta_key = 'example_featured'
AND $meta_table.meta_value = 1
)
AND $meta_table.meta_key = 'example_sort'
GROUP BY $post_table.ID
ORDER BY $meta_table.meta_value+0 ASC
LIMIT 0, 8";
my_var_dump($fs_query);
TABLE 1 : wp_posts
+------------+--------------+----------------+ | ID | post_type | post_status | +------------+--------------+----------------+ | 1 | services | publish | +------------+--------------+----------------+
TABLE 2 : wp_postmeta
+------------+------------+------------------+--------------+ | ID | post_id | meta_key | meta_value | +------------+------------+------------------+--------------+ | 1 | 1 | example_featured | 1 | | 2 | 1 | example_sort | 5 | +------------+------------+------------------+--------------+
Struggling with making this SQL query:
I want all the post_id where post_type
= 'services', and post_status
= 'publish', and the value for the associate meta_value
(example_featured
) is 1 (one). And then want to sort the result using another meta value I passed using another meta_key
(example_sort
). If I remove AND $meta_table.meta_key = 'example_sort'
from the query then get those post IDs, but with the query above I get nothing at all.
How can I do it?
$wpdb->prefix . 'posts'
to$wpdb->posts
and$wpdb->prefix . 'postmeta'
to$wpdb->postmeta
. codex.wordpress.org/Class_Reference/wpdb#Tables – Nathan Dawson