function count_related_posts_shortcode($atts) {
global $post, $wpdb;
if ( ! isset($post->ID) ) {
return '0';
}
$atts = shortcode_atts([
'cpt' => '',
], $atts, 'count-related-posts');
$current_post_id = (int) $post->ID;
$cpt = sanitize_text_field($atts['cpt']);
if (empty($cpt)) {
return '0';
}
$table = $wpdb->prefix . 'voxel_relations';
// Get related children (where current post is parent)
$children = $wpdb->get_col(
$wpdb->prepare(
"SELECT child_id FROM $table WHERE parent_id = %d",
$current_post_id
)
);
// Get related parents (where current post is child)
$parents = $wpdb->get_col(
$wpdb->prepare(
"SELECT parent_id FROM $table WHERE child_id = %d",
$current_post_id
)
);
// Merge and dedupe
$related_ids = array_unique(array_merge($children, $parents));
if (empty($related_ids)) {
return '0';
}
$count = 0;
foreach ($related_ids as $related_id) {
$related_post = get_post($related_id);
if (
$related_post &&
$related_post->post_status === 'publish' &&
$related_post->post_type === $cpt
) {
$count++;
}
}
return $count;
}
add_shortcode('count-related-posts', 'count_related_posts_shortcode');