Skip to content

Snippets / PHP

PHP

Count Related Posts

A ashleyyoung · 152 views · Updated 1 year ago
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.
[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 · 58 lines

Discussion

Ask a question or share how you used this.

Log in to join the discussion.

No comments yet — be the first.

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.