Looking to get the number of CPT B posts related to a CPT A post when using a Relationship field with ACF?
Here’s a custom function for that:
/**
* Get the count of related posts for the current post
* or a specific post ID
*
* @param string $field_name The relationship field name slug.
* @param int $post_id Optional. The ID of the post. Defaults to current post ID.
* @return int Number of related posts
*/
function bl_get_related_posts_count( string $field_name, int $post_id = 0 ): int {
$post_id = $post_id ?: get_the_ID();
$related_posts = get_field( $field_name, $post_id );
if ( ! $related_posts || ! is_array( $related_posts ) ) {
return 0;
}
return count( $related_posts );
}
bl_get_related_posts_count( 'related_cities' ), for example, can be used to output the number of cities for each country in a country query loop where related_cities is the Relationship field name.
To use this in Bricks with echo dynamic data tag, whitelist it:
add_filter( 'bricks/code/echo_function_names', function() {
return [
'bl_get_related_posts_count'
];
} );
and then
{echo:bl_get_related_posts_count(related_cities)}
1 comment
Mounika
Amazing, I tried this and it's working.
Thank you.