Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
    
As a side note, did you try count($jobs) or print_r($jobs) just to see the original results of the query? –  redconservatory Aug 22 '11 at 12:35
    
no, just tried and it doesn't o anything useful. –  Dan Lee Aug 22 '11 at 12:51

2 Answers 2

up vote 10 down vote accepted

The 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;
share|improve this answer
    
That does the job! –  Dan Lee Dec 13 '11 at 11:11
    
I'm glad it helped –  Mamaduka Dec 13 '11 at 15:49
    
Thanks @Mamaduka –  Sagive SEO Dec 21 '11 at 22:08
    
You need to accept this answer, by clicking the checkmark beneath the vote count, in the upper left-hand corner of the answer. –  Chip Bennett Feb 10 '12 at 13:36

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>";
share|improve this answer
    
It is a very bad practive to use plain sql in your code. There are a lot of WP wrapper functions that do the same thing and even more. –  NoSense Oct 5 at 14:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.