13th Dec '24
/
1 comment

ACF Relationship: Count of Related Posts

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)}

Get access to all 612 Bricks code tutorials with BricksLabs Pro

1 comment

  • Mounika

    Amazing, I tried this and it's working.

    Thank you.

Leave your comment

 

Related Tutorials..

Pro
Random images from ACF Options Gallery in Bricks

Random images from ACF Options Gallery in Bricks

This Pro tutorial provides the steps to output images from an ACF Gallery-type custom field in a Bricks query loop randomly with each image appearing…
Categories:
Pro
Custom Dynamic Data Tags for ACF Field Label, Prefix and Suffix in Bricks

Custom Dynamic Data Tags for ACF Field Label, Prefix and Suffix in Bricks

Bricks lacks built-in dynamic tags for ACF field labels, prefixes, and suffixes. This tutorial shows how to add them using custom dynamic tags.
Categories:
Pro
Featured Image’s Meta in a Bricks Posts Query Loop

Featured Image’s Meta in a Bricks Posts Query Loop

How to output values of custom fields for the featured image of current post in a query loop
Categories:
Tags:
Pro
ACF Image Data in Bricks

ACF Image Data in Bricks

Displaying Alt text, Caption, Title and URL of an ACF image field for posts in a query loop.
Categories:
Tags:
Pro
Programmatically populating ACF field values in WordPress

Programmatically populating ACF field values in WordPress

An example of how to set the values of a Select-type field with the names and labels of all public post types.
Categories:
Pro
Post-specific ACF Repeater Galleries as Sliders in Bricks

Post-specific ACF Repeater Galleries as Sliders in Bricks

How to output ACF Repeater field rows with the images of the Gallery-type sub field as a slider.