计算帖子数(自定义帖子类型)查询问题


11

我正在尝试计算自定义帖子类型“工作”的总帖子数。当我知道有帖子时,我的查询只会返回“ 0”。我不认为这是在检查帖子类型是否包含帖子,但是我不知道为什么...有什么想法吗?

<?php $jobs = new WP_Query(array( 'post_type' => 'jobs' ));?>
<?php if ($jobs->have_posts()) { 

    $count_posts = wp_count_posts()->publish; 
    if ( $count_posts == "1" ) { 
        echo "<h2>There is currently one vacancy...</h2>"; }
    else { echo "<h2>There are currently  $count_posts vacancies...</h2>"; }

} else { ?>
<h2>There are currently no vacancies.</h2>
<?php } ?>

作为附带说明,您是否尝试过count($ jobs)或print_r($ jobs)只是为了查看查询的原始结果?
redconservatory 2011年

不,只是尝试过,它没有任何用处。
李丹(Dan Lee)

Answers:



-1

将它们替换为您的meta_key和meta_value:

$meta_key = 'x';
$meta_value = '2';

$sql = "SELECT count(DISTINCT pm.post_id)
FROM $wpdb->postmeta pm
JOIN $wpdb->posts p ON (p.ID = pm.post_id)
WHERE pm.meta_key = '$meta_key'
AND pm.meta_value = '$meta_value'
AND p.post_type = 'post'
AND p.post_status = 'publish'
";

$count = $wpdb->get_var($sql);
echo "<p>Count is: $count</p>";

在您的代码中使用纯SQL是非常糟糕的。有很多WP包装函数可以完成相同的任务甚至更多。
NoSense 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.