How to quickly count child posts in a query
I have a website centered around music. I have 3 main post types- ‘Artist’, ‘Release’, and ‘Version’. There are 4 types of ‘Version’- album, single, video, misc.
Artist is parent of Release. (artist has a single -> many relationship with releases)
Release is a parent of Version. (Release has a single-> many relationship with version)
I’ve established these relationships in the plugin toolset types.
In my single-artist page, I have releases displayed in sections. Here’s an example of the code to display all albums by an artist.
<?php
$album_args = array(
'post_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'release-format',
'field' => 'slug',
'terms' => 'album',
),
),
);
$album_posts = types_child_posts('release', $album_args);
// sort alphabetically by firstname and lastname
usort($album_posts, 'compare_fullname');
$url = esc_url( home_url() );
?>
<div class="row row-cols-1 justify-content-center">
<?php foreach ($album_posts as $child_post) { ?>
<div class="col py-1">
<?php include get_template_directory() . '/includes/containers/artist-page-container.php' ;?>
<?php
$versionID= $child_post->ID;
$version_count = array(
'post_type' => 'album',
'post_per_page' => -1,
'meta_query' => array(
array(
'key' => '_wpcf_belongs_release_id',
'value' => $versionID,
)
),
);
$version_counter = types_child_posts('release', $version_count);
$count=0;
foreach ($version_counter as $counter_child_post ) {
$count++;
}
if ($count==1){
echo "$count version";
}else{
echo "$count versions";
}
?>
</div>
<?php } ?>
So… In the foreach loop, while it is going through a release- it takes a new dive into all the child posts of this release.
This count is VERY slow, when I add this count into each section, it can take 15 seconds or more for a big artist page to load. What is a better way to count these?
I think, specifically, I need to lose the meta_query and the _wpcf_belongs_release_id and instead replace it with a different way of finding all the related child posts of this post. Is there a better way to do this?
The amount of versions doesn’t change until I upload a new version (not often).
Is there a way to run this count BEFORE the user ever sees the page? Can I run the count on the admin side and just associate the final number with the release as a meta_field or some such thing?
Thanks!
Leave an answer