Custom shortcode to display count of related posts

A general purpose shortcode to display the number of posts related to the current post in a specified relationship.

/**
 * Register connections shortcode
 *
 * @att (string) relationship : post relationship slug
 * @return count of connected posts
 */
add_shortcode( 'connections', function( $atts = [] ){
  
    // provide defaults
    $atts = shortcode_atts( 
        array(
            'relationship'      =>   '',
        ), 
        $atts
    );
  
    global $post;
    $count = 0;
  
    $relationship = toolset_get_relationship( $atts['relationship'] );
  
    if ( $relationship ) {
  
        $parent = $relationship['roles']['parent']['types'][0];
        $child = $relationship['roles']['child']['types'][0];
        $type = $post->post_type;
  
        $origin = ( $parent == $type ) ? 'parent' : 'child';
  
        // Get connected posts
        $connections = toolset_get_related_posts( $post->ID, $atts['relationship'], array(
        	'query_by_role' => $origin,
        	'role_to_return' => 'other',
        	'need_found_rows' => true )
    	);
    	$count = $connections['found_rows'];
  
    }
  
    return $count;
});

You just need to pass the relationship slug via the ‘relationship’ attribute, e.g.

[connections relationship="project-task"]

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments