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

时间:2011-08-22 作者:Dan Lee

我试图计算自定义职位类型“jobs”的总职位数。当我知道有帖子时,我的查询只返回“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 } ?>

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

这个wp_count_posts 函数具有参数$type 要使post type计数,如果要获取作业数,则应使用此参数

像这样:

$count_posts = wp_count_posts( \'jobs\' )->publish;

SO网友:urooj

用meta\\u键和meta\\u值替换这些值:

$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>";

SO网友:Bruno Wego

另一种方法是使用WP-CLI:

wp eval \'echo wp_count_posts( "post" )->publish;\'; echo

结束

相关推荐