This site is running Voxel Theme Version: 1.5.5.1 | Elementor Plugin Version: 3.28.4

Join the Voxel Guide Community!

Get Involved

Count Related Posts

Description/Instructions

A shortcode that looks at the current post ID that the shortcode is used on and then checks relationships it has with the post type set in the shortcode variable.

Instructions

[count-related-posts cpt="CPTKEY"]

Replace CPTKEY with the key of the post type you want to count.

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');

  • PHP
Copy Code

Let's Chat About this Snippet

Chat Toggle
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Ask me anything about Voxel!
Send
Powered by AI24