Skip Navigation

[Resolved] Define conditional block to test if child relationship exists

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

This topic contains 2 replies, has 2 voices.

Last updated by John 6 months, 2 weeks ago.

Author
Posts
#2696585

Tell us what you are trying to do?

Define a conditional block that will test if a child relationship exists (IE On a Series Page only display blocks inside condition if Series has Bundles attached. I know it probably needs a shortcode, but I could not find a good example.

Is there any documentation that you are following?

Is there a similar example that we can see?

What is the link to your site?

hidden link

#2696674

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi John

Let me share a general purpose shortcode you can use which simply returns the number of posts connected to the current post in a specified relationship (so you can test for zero).

/**
 * 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;
});

So in the context of a project post, this would show how many tasks belonged to it:

[connections relationship="project-task"]

To use this in a conditional shortcode or block, you will need to register the custom shortcode at Toolset > Settings > Front-end content.

#2696738

Thanks will confirm later today

#2697640

Thanks Nigel