WordPress.org

Ready to get started?Download WordPress

Forums

Count custom posts within a list of categories (1 post)

  1. ryancraigmurray
    Member
    Posted 1 year ago #

    Hi,

    I have a 'foreach' loop printing out a category list (below). I'd like to display totals next to each for the amount of a particular custom post. I'm using a function (below) that will do the counting for you if you pass it variables, however, I can't get it to work. I don't know wether it's because I'm trying to use it with custom posts or not. Any help would be much appreciated.

    foreach ($locationsList as $location) {
    	$cats_to_count = $parentCategory_id;
    	$cats_to_count .= ", ";
    	$cats_to_count .= $location->term_id;
    	wdd_in_category_count($cats_to_count);
    	?><li><a <?php if($location->slug==$locationSlug){ echo "class=\"active\""; } ?> href="/<?php echo $parentpageTitle ?>/?location=<?php echo $location->slug ?>"><?php echo $location->name; ?></a></li><?
    }

    This is the function I'm trying to use.

    function wdd_in_category_count($catslugs = '', $display = true) {
    	global $wpdb;
    
    	$post_count = 0;
    	$slug_where = '';
    	$catslugs_arr = split(',', $catslugs);
    
     	foreach ($catslugs_arr as $catslugkey => $catslug) {
    		if ( $catslugkey > 0 ) {
    			$slug_where .= ', ';
    		 }
    
     		$slug_where .= "'" . trim($catslug) . "'";
    	}
    
    	$slug_where = "cat_terms.slug IN (" . $slug_where . ")";
    
    	$sql =	"SELECT	COUNT( DISTINCT cat_posts.ID ) AS post_count " .
    			"FROM 	" . $wpdb->term_taxonomy . " AS cat_term_taxonomy INNER JOIN " . $wpdb->terms . " AS cat_terms ON " .
    						"cat_term_taxonomy.term_id = cat_terms.term_id " .
    					"INNER JOIN " . $wpdb->term_relationships . " AS cat_term_relationships ON " .
    						"cat_term_taxonomy.term_taxonomy_id = cat_term_relationships.term_taxonomy_id " .
    					"INNER JOIN " . $wpdb->posts . " AS cat_posts ON " .
    						"cat_term_relationships.object_id = cat_posts.ID " .
    			"WHERE 	cat_posts.post_status = 'publish' AND " .
    					"cat_term_taxonomy.taxonomy = 'category' AND " .
    					$slug_where;
    
    	$post_count = $wpdb->get_var($sql);
    
    	if ( $display ) {
    		echo $post_count;
    	} 
    
    	return $post_count; 
    
    }

Topic Closed

This topic has been closed to new replies.

About this Topic

  • RSS feed for this topic
  • Started 1 year ago by ryancraigmurray
  • This topic is not resolved
  • WordPress version: 3.4.2