You have a couple of problems with your code
-
customtaxonomy=$mytaxonomyis incorrect. First of all, there is no parameter calledcustomtaxonomyinget_posts. Secondly, your syntaxing is wrong. If you make use of a varaible, your syntaxing should look like this'post_type=myposttype&customtaxonomy=' . $mytaxonomy . '&posts_per_page=-1' -
You should make use of a proper
tax_queryto get your posts. You should also make use ofget_termsto get all the terms of the selected taxonomy
Here is how your code should look like: (I have also made the post type a variable)
function my_posts_count($taxonomy, $post_type) {
$terms = get_terms( $taxonomy, 'fields=ids' );
$args = [
'post_type' => $post_type,
'nopaging' => true,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $terms
]
],
];
$mytaxonomy = get_posts( $args );
$mytaxonomy_posts_count = count($mytaxonomy);
echo $mytaxonomy_posts_count;
}
Please note, I have used syntaxing that will not work pre PHP 5.4
You can then use the code as follow
my_posts_count('category', 'post');
EDIT
Rethinking of @birgire comments
I feel we should
returnthe count since we use theget_prefix, even though WordPress breaks it’s own rule regarding this semi naming convention
I have removed the get_ prefix from your function name. In WordPress, functions which have the get_ prefix returns its output, while functions without the get_ prefix echo its output
The correct way to use your function when using the get_ prefix is as follows
function get_my_posts_count($taxonomy, $post_type) {
$terms = get_terms( $taxonomy, 'fields=ids' );
$args = [
'post_type' => $post_type,
'nopaging' => true,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $terms
]
],
];
$mytaxonomy = get_posts( $args );
$mytaxonomy_posts_count = count($mytaxonomy);
return $mytaxonomy_posts_count;
}
And in your template call it like this
echo get_my_posts_count('category', 'post');