Displaying internal linkbacks on WordPress


I have written a lot of blog posts. In some of those posts I link to other posts on my site. What's the easiest way of displaying those internal incoming links?

Here's what it looks like:

Screenshot of my website. The headline says "What links here from around this site." Underneath are three links.

Code

All we need to do is search WordPress for the URl of the current page. Loop through the results. Then display those links.

PHP PHP$the_query = new WP_Query(
    array(
        's' => get_the_permalink(), // This post
        'post_type' => 'post',      // Only posts, not pages
        "posts_per_page" => "-1",   // Get all results
        "order" => "ASC"            // Oldest first
    )
);

//  Nothing to do if there are no inbound links
if ( !$the_query->have_posts() ) {
    return;
}

//  Loop through the posts
while ( $the_query->have_posts() ) {
    //  Set it up
    $the_query->the_post();
    $id            = get_the_ID();
    $title         = esc_html( get_the_title() );
    $url           = get_the_permalink();
    $comment_date  = get_the_date( "c" );
    $comment_year  = get_the_date( "Y" );

    //  Get the thumbnail
    if ( has_post_thumbnail( $id) ) {
        $thumb = get_the_post_thumbnail( $rid, 'full',
            array( "class"   => "related-post-img",
                   "loading" => "lazy" //   Lazy loading and other attributes
            )
        );
    } else {
        $thumb = null;
    }

    //  Create the HTML for the incoming link
    echo <<<EOT
    <li>
        <a href="$url">
            $thumb
            $title
        </a>
        <time datetime="$comment_date">$comment_year</time>
    </li>
    EOT;

}

In order to reduce duplicates, you may also want to disable self-ping. Here's some code you can stick in your functions.php:

PHP PHPfunction no_self_ping( &$links ) {

    $home = esc_url( home_url() );

    // Process each link in the content and remove if it matches the current site URL
    foreach ( $links as $l => $link ) {
        if ( 0 === strpos( $link, $home ) ) {
            unset( $links[ $l ] );
        }
    }
}
add_action( 'pre_ping', 'no_self_ping' );

Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

One thought on “Displaying internal linkbacks on WordPress”

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">