[wp-trac] [WordPress Trac] #39372: Allow count for wp_terms query to count other post statuses as well as published posts
WordPress Trac
noreply at wordpress.org
Thu Dec 29 22:50:34 UTC 2016
#39372: Allow count for wp_terms query to count other post statuses as well as
published posts
-------------------------------+------------------------------
Reporter: roperjonathan | Owner:
Type: feature request | Status: new
Priority: normal | Milestone: Awaiting Review
Component: General | Version: 4.7
Severity: normal | Resolution:
Keywords: reporter-feedback | Focuses: performance
-------------------------------+------------------------------
Comment (by roperjonathan):
So I recently had an example where I needed to count the number of posts
associated with each term for a taxonomy but both for posts that are
published and that are drafts.
In order to do this I did the following:
{{{#!php
<?php
if(!empty($slug)) {
$terms_args = array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'fields' => 'all',
'pad_counts' => true,
);
$terms = get_terms($slug, $terms_args);
return $terms;
}
}}}
and then once I got all of the terms for a particular taxonomy, then do a
WP Query and then if the count returns 1 or more than show the option in a
dropdownlist with the count:
{{{#!php
<?php
if ( ! empty( $terms ) ) {
foreach ( $terms as $term ) {
$st = $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->posts p
INNER JOIN $wpdb->term_relationships tr
ON (p.ID = tr.object_id)
INNER JOIN $wpdb->term_taxonomy tt
ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
WHERE
tt.term_id = %d
AND (p.post_status = 'publish'
OR p.post_status = 'in-progress');",
$term->term_id);
$results = $wpdb->get_var($st);
if($results){
$output .= '<option value="' . $term->slug . '">' .
$term->name . ' (' . $results . ') </option>';
}
}
}
}}}
I would have liked it so that there would be an option in the $terms_args
to return and count terms that have posts of a certain post status
associated to them. So for example, like with the post_status option you
can use with the get_posts function. This would then mean I wouldn't have
needed the second part of the code.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/39372#comment:2>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list