0

How do I get the trackback count of a post in wordpress without writing an SQL query?

I tried searching Brave Search and I couldn't find anything helpful. To fetch the amount of comments a post has, get_comments_number() is the wordpress protocol function for it. But what if I want to fetch the amount of trackbacks a post has?

And also, do I have to be inside "the loop" to do this? What if I'm outside the loop?

1 Answer 1

3

You can specify what kind of comment you want to retrieve using get_comments().

// Assumes you've set $post_id somewhere.
$args = array(
    'type' => 'trackback',
    'post_id' => $post_id,
);
$trackbacks = get_comments( $args );
$trackback_count = count( $trackbacks );

Edited to add: As Sally CJ points out in the comments, you can do this in just one step:

// Assumes you've set $post_id somewhere.
$args = array(
    'type'    => 'trackback',
    'post_id' => $post_id,
    'count'   => true,
);
$trackback_count = get_comments( $args );

This code is untested but it should provide you a starting place.

As far as being inside/outside The Loop: The above code should work just fine either way, as long as you've got a way to get the post ID (get_the_ID() should work in The Loop; if you've got a WP_Post object called $my_post, then $my_post->ID should get it for you).

References

2
  • 2
    👍, but the count argument can be used to get only the total number of trackbacks/comments, e.g. $trackback_count = get_comments( array( 'type' => 'trackback', 'post_id' => $post_id, 'count' => true ) ); ..
    – Sally CJ
    May 20 at 0:52
  • 1
    Good point, I've added that to the answer. Thanks!
    – Pat J
    May 20 at 2:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.