bbp_get_child_counts( int $parent_id )
Query the database for child counts, grouped by type & status
Description Description
Parameters Parameters
- $parent_id
-
(Required)
Source Source
File: includes/common/functions.php
function bbp_get_child_counts( $parent_id = 0 ) {
// Create cache key
$parent_id = absint( $parent_id );
$key = md5( serialize( array( 'parent_id' => $parent_id, 'post_type' => bbp_get_post_types() ) ) );
$last_changed = wp_cache_get_last_changed( 'bbpress_posts' );
$cache_key = "bbp_child_counts:{$key}:{$last_changed}";
// Check for cache and set if needed
$retval = wp_cache_get( $cache_key, 'bbpress_posts' );
if ( false === $retval ) {
// Setup the DB & query
$bbp_db = bbp_db();
$sql = "SELECT
p.post_type AS type,
p.post_status AS status,
COUNT( * ) AS count
FROM {$bbp_db->posts} AS p
LEFT JOIN {$bbp_db->postmeta} AS pm
ON p.ID = pm.post_id
AND pm.meta_key = %s
WHERE pm.meta_value = %d
GROUP BY p.post_status, p.post_type";
// Get prepare vars
$post_type = get_post_type( $parent_id );
$meta_key = "_bbp_{$post_type}_id";
// Prepare & get results
$query = $bbp_db->prepare( $sql, $meta_key, $parent_id );
$results = $bbp_db->get_results( $query, ARRAY_A );
// Setup return value
$retval = wp_list_pluck( $results, 'type', 'type' );
$statuses = get_post_stati();
// Loop through results
foreach ( $results as $row ) {
// Setup empties
if ( ! is_array( $retval[ $row['type'] ] ) ) {
$retval[ $row['type'] ] = array_fill_keys( $statuses, 0 );
}
// Set statuses
$retval[ $row['type'] ][ $row['status'] ] = bbp_number_not_negative( $row['count'] );
}
// Always cache the results
wp_cache_set( $cache_key, $retval, 'bbpress_posts' );
}
// Make sure results are INTs
return (array) apply_filters( 'bbp_get_child_counts', $retval, $parent_id );
}
Changelog Changelog
| Version | Description |
|---|---|
| 2.6.0 | Introduced. |