Thank you for waiting and for sharing these details.
During testing on my website, I was able to make this work, using the following custom shortcode:
add_shortcode('process-mh-relationships', 'process_mh_relationships_func');
function process_mh_relationships_func( $atts ) {
$a = shortcode_atts( array(
'id' => ''
), $atts );
if (!empty($a['id'])) {
$parent_post_slug = 'major-hazard';
$child_post_slug = 'jci-hazard-product';
$relationship_slug = 'manual-major-hazard-jci-hazard-product';
// get target major Hazard post's 'haz_id' custom field values
$parent_haz_ids = types_render_field( "haz_id", array( 'item' => $a['id'], 'separator' => ',') );
// create an array of those values
$parent_haz_ids_arr = explode(',', $parent_haz_ids);
// get existing related hazard products so that they can be excluded from new processing
$get_related_hazard_results = toolset_get_related_posts( $a['id'], $relationship_slug, 'parent', 9999999, 0, array(), 'post_id', 'child' );
// get the list of all hazard product posts, where the 'haz_id' custom field value is the same as the target major Hazard post, excluding those which are already connected
$args = array(
'posts_per_page' => -1,
'post_type' => $child_post_slug,
'post_status' => 'publish',
'post__not_in' => $get_related_hazard_results,
'fields' => 'ids',
'meta_query' => array(
array(
'key' => 'wpcf-haz_id',
'value' => $parent_haz_ids_arr,
'compare' => 'IN',
),
),
);
$child_post_list = get_posts( $args );
// if some child post are found which need to be connected
if (!empty($child_post_list)) {
foreach ( $child_post_list as $post_item ) {
// connect those posts
$connect_results[] = toolset_connect_posts( $relationship_slug, $a['id'], $post_item );
}
ob_start();
echo '<pre>';
print_r($connect_results);
echo '</pre>';
return ob_get_clean();
}
else
{
return "No posts were found which need to be connected!";
}
}
else
{
return "No parent post ID provided";
}
}
To run it for a parent "COVID-19 Global Pandemic" major hazard post with ID "255519", you can use the shortcode as:
[process-mh-relationships id='255519']
The shortcode will first get all the values of the custom field "haz_id" from this parent post and then look for all the JCI hazard posts which have the same "haz_id" field values and are not already connected to this target parent post. In the last step, those matched posts are connected to the parent post in the relationship too.
Note: The custom code examples from our forum are shared to get you started in the right direction. You're welcome to adjust them as needed and for more personalized customization assistance, you can consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/