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 630 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
ACF Repeater Row Count Condition in Bricks

ACF Repeater Row Count Condition in Bricks

This Pro tutorial provides the steps to output elements on single posts (of any post type) in Bricks only if a specific ACF Repeater-type of…
Categories:
Pro
ACF Post Object Query Loop inside a Posts Query Loop in Bricks

ACF Post Object Query Loop inside a Posts Query Loop in Bricks

How to loop through a CPT and within each post, output a list of related posts.
Categories:
Pro
Related FAQs on Product pages Based on Product Category Taxonomy in Bricks

Related FAQs on Product pages Based on Product Category Taxonomy in Bricks

On product pages, we show all the FAQs associated with the current WooCommerce product's product categories.
Categories:
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
Filtering ACF Relationship Query by Post Meta in Bricks

Filtering ACF Relationship Query by Post Meta in Bricks

How to filter the posts of a post type related to another post type based on the value of a True / False type ACF…
Pro
ACF Taxonomy Field Value in Single Posts

ACF Taxonomy Field Value in Single Posts

Consider this scenario: CPT: Movie Movie CPT Taxonomy: Movie Genre Movie Genre Taxonomy's field: Genre Color Each movie will have only genre set. The requirement…
Categories:
Tags: