在$wpdb查询中包括POST_STATUS检查

时间:2016-02-14 作者:patrick

我有一个函数,可以从数据库中返回与产品ID和帖子元ID匹配的发布帖子的计数(两者都是产品类型)。我意识到这个查询也会返回未发布的帖子。

我已经试了几个小时,想知道如何将防御检查包括在内,只包括那些post_status 属于publish

public function get_number_of_stars_for( $star_value ) {
        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(wpm2.`meta_value`)
                    FROM $wpdb->postmeta as wpm2,
                    (
                        SELECT * FROM $wpdb->postmeta WHERE `meta_value` = %d AND `meta_key` = \'review_product\'
                    ) as wpm1
                    WHERE wpm1.`post_id` = wpm2.`post_id` AND wpm2.`meta_key` = \'review_rating\' AND wpm2.`meta_value` = %d
                ",
                $this->post->ID,             
                $star_value
            )
        );
    }

1 个回复
SO网友:MikeNGarrett

简短回答要获取帖子状态,您需要JOIN 基于post_id 你从wpm1wpm2 并扩展您的WHERE 子句使用该联接数据。

建议另一方面,您可以使用WP_Query 处理此内容。请参见下面的快速示例。我强烈建议在将此代码添加到您的站点之前对其进行测试。

<?php
$args = array(
    \'fields\' => \'ids\',
    \'posts_per_page\' => 1, // This is a heavy-handed approach to limit result to one
    \'meta_query\' => array(
        array(
            \'key\'     => \'review_product\',
            \'value\'   => $this->post->ID,
            \'compare\' => \'=\',
        ),
    ),
);
$query = new WP_Query( $args );
$all_ids = $query->posts[0]; // Most likely want to change this to a foreach so you can find the right value

$args2 = array(
    \'fields\' => \'ids\',
    \'meta_query\' => array(
        array(
            \'key\'     => \'review_rating\',
            \'value\'   => $all_ids,
            \'compare\' => \'=\',
        ),
    ),
);
$query2 = new WP_Query( $args2 );
return $query2->post_count;