$wpdb->get_var未返回结果

时间:2012-07-02 作者:JohnMerlino

我启动了mysql并确认此查询返回一个结果:

mysql> SELECT * FROM wp_posts WHERE post_parent = 68 AND post_type = \'attachment\' AND post_name = \'side-logo-auto2\' LIMIT 1;
1 row in set (0.00 sec)
在我的模板中,我尝试了同样的事情:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();

    //$wpdb->posts is wp_posts table
    //$post->ID is current post of post_type page, 
    //that is associated with page of this template

    global $wpdb;
    $image = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT * FROM $wpdb->posts
             WHERE post_parent = %d
             AND post_type = %s
             AND post_name = %s
             LIMIT 1
            ",
            $post->ID,
            \'attachment\',
            \'side-logo-auto2\'
        )
    );
    echo "The image id is {$image->ID}";
    echo wp_get_attachment_image($image->ID);

endwhile; endif; ?> 
$post->ID返回68。然而,分配给$image的值不是记录,而是空值。

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

$wpdb->get_var 返回单个变量,但SQL语句SELECT * 它返回一行多列。

您需要将SQL语句更改为SELECT ID ... 而不是SELECT * ...

结束

相关推荐

WP Query Returning All Posts

我有一个自定义的WP查询,它返回每个帖子,而不仅仅是查询指定的帖子。我似乎找不到代码有什么问题,所以我肯定遗漏了什么://Process incoming variable if(!empty($_REQUEST[\'region\'])){ $region = $_REQUEST[\'region\']; } else { $region = NULL; } if (empty($region)) { echo \"