Prepare WPDB with meta key and meta value

admin2025-04-19  0

I'm trying to prepare WPDB by post type, meta key, and meta value

global $post;
global $wpdb;
$rid = absint($_POST["rid"]); // number
$last_id = absint($_POST["lastID"]); // post ID
$query = $wpdb->prepare(
    "
        SELECT ID
        FROM $wpdb->posts
        WHERE ID > %d
        AND wp_posts.post_type = 'room'
        AND wp_postmeta.meta_key = 'rid'
        AND wp_postmeta.meta_value = %s
        ORDER BY wp_posts.ID DESC
        LIMIT 0, 1", $last_id, $rid);
$results = $wpdb->get_results( $query );
foreach ( $results as $row ) {
    echo $row->ID;
}
die();

All I want to do is get the last ID that fits the criteria

I'm trying to prepare WPDB by post type, meta key, and meta value

global $post;
global $wpdb;
$rid = absint($_POST["rid"]); // number
$last_id = absint($_POST["lastID"]); // post ID
$query = $wpdb->prepare(
    "
        SELECT ID
        FROM $wpdb->posts
        WHERE ID > %d
        AND wp_posts.post_type = 'room'
        AND wp_postmeta.meta_key = 'rid'
        AND wp_postmeta.meta_value = %s
        ORDER BY wp_posts.ID DESC
        LIMIT 0, 1", $last_id, $rid);
$results = $wpdb->get_results( $query );
foreach ( $results as $row ) {
    echo $row->ID;
}
die();

All I want to do is get the last ID that fits the criteria

Share Improve this question asked Oct 16, 2019 at 9:13 LeopoldLeopold 76 bronze badges 3
  • And what is your question? Or to ask another way: how does your current code break / not do what it is supposed to? What error messages do you get? – kero Commented Oct 16, 2019 at 9:14
  • I don't get an error. It just doesn't return post. I have to remove the meta lines to get return. The meta value and key are correct. – Leopold Commented Oct 16, 2019 at 9:22
  • %s should be %d yes? But I already used %d once so do I need to change it to differentiate? – Leopold Commented Oct 16, 2019 at 9:45
Add a comment  | 

1 Answer 1

Reset to default 0

If you run this query manually, you should get a response like

(1054, "Unknown column 'wp_postmeta.meta_key' in 'where clause'")

Long story short, wp_postmeta.meta_key is not a valid column of wp_posts. You need to JOIN the postmeta table to be able to use its columns. (There are many resources out there that explain JOIN, one would be this answer.)

$query = $wpdb->prepare(
    "
        SELECT p.ID
        FROM {$wpdb->posts} AS p
        INNER JOIN {$wpdb->postmeta} AS pm
            ON p.ID = pm.post_id AND pm.meta_key = %s
        WHERE p.ID > %d
        AND p.post_type = %s
        AND pm.meta_value = %s
        ORDER BY p.ID DESC
        LIMIT 0, 1
    ",
    'rid',
    $last_id,
    'room',
    $rid
);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745077011a283627.html

最新回复(0)