goranseric
6/14/2014 - 8:26 PM

Shared taxonomy across 2 or more custom post types, correct posts count

Shared taxonomy across 2 or more custom post types, correct posts count

// Create a function that will count posts

function gs_get_term_post_count_by_type($term,$taxonomy,$type){

  $args = array( 
    'fields' =>'ids',
    'numberposts' => -1,
    'post_type' => $type, 
     'tax_query' => array(
        array(
            'taxonomy' => $taxonomy,
            'field' => 'id',
            'terms' => intval($term)
        )
      )
   );
   $ps = get_posts( $args );

   if (count($ps) > 0){
       return count($ps);
   }else{
       return 0;
   }
 }
 
// Remove default posts column and add an new one that will be populated

add_filter('manage_edit-sharedtaxonomy_columns','gs_cpt_columns');

function gs_cpt_columns($columns){
$screen = get_current_screen();
$type = get_post_type_object( $screen->post_type );

unset($columns['posts']);

$columns['items_count'] = $type->labels->name;;

return $columns;
}

// Populate custom column with post count

add_filter('manage_sharedtaxonomy_custom_column','gs_cpt_alter_count',10,3);

function gs_cpt_alter_count($value, $column_name, $id ){
	$screen = get_current_screen();
    if( 'items_count' == $column_name )
        return ca_get_term_post_count_by_type($id,'region',$screen->post_type);

    return $value;
}