admin管理员组文章数量:1332389
I'm trying to count the number of total posts of a custom post type "jobs". My query just returns "0" when I know there are posts. I don't think it is checking that the post type has posts, but I'm clueless as to why... any ideas?
<?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 } ?>
I'm trying to count the number of total posts of a custom post type "jobs". My query just returns "0" when I know there are posts. I don't think it is checking that the post type has posts, but I'm clueless as to why... any ideas?
<?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 } ?>
Share
Improve this question
asked Aug 22, 2011 at 12:26
Dan LeeDan Lee
5472 gold badges6 silver badges14 bronze badges
2
- As a side note, did you try count($jobs) or print_r($jobs) just to see the original results of the query? – redconservatory Commented Aug 22, 2011 at 12:35
- no, just tried and it doesn't o anything useful. – Dan Lee Commented Aug 22, 2011 at 12:51
3 Answers
Reset to default 58The wp_count_posts
function has parameter $type
for post type to count, you should use this parameter if you want to get number of jobs
like so:
$count_posts = wp_count_posts( 'jobs' )->publish;
Replace these with your meta_key and 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>";
Another way, using WP-CLI:
wp eval 'echo wp_count_posts( "post" )->publish;'; echo
本文标签: Counting the number of posts (custom post type) Query problems
版权声明:本文标题:Counting the number of posts (custom post type) Query problems 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742287984a2447275.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论