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:

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
$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 <<<color: #795E26;">EOT <li> <a href="$url"> $thumb $title </a> <time datetime="$comment_date">$comment_year</time> </li> color: #795E26;">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
function 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' );
Earlier this year, after basically two decades of searching, I finally had an internal backlinks solution thanks to an arduous process involving ChatGPT. It solved…
Reply to original comment on bix.blog
|More comments on Mastodon.