使用元键和元值准备WPDB

时间:2019-10-16 作者:Leopold

我试图通过post类型、元键和元值来准备WPDB

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();
我只想得到符合条件的最后一个ID

1 个回复
最合适的回答,由SO网友:kero 整理而成

如果手动运行此查询,应该会得到如下响应

(1054,“where子句”中的未知列“wp\\u postmeta.meta\\u key”)

长话短说,wp_postmeta.meta_key 不是的有效列wp_posts. 你需要JOIN Posteta表可以使用其列。(有很多资源可以解释JOIN, 一个是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
);

相关推荐

在WordPress中使用wpdb查询没有结果

除非我将字符串标题改为“Gocomma 10W QI无线快速充电器车载支架”,否则我不会得到任何结果。。。 $title1=\"Gocomma 10W QI Wireless Fast Charger Car Mount Holder - 2pcs (it)\"; $sql = $wpdb->prepare(\"SELECT * FROM $wpdb->posts WHERE post_title LIKE \'%%%s%%\' and post_statu