bix.paste.lol / display_backlinks_shortcode.php · 2 weeks ago·

function display_backlinks_shortcode($atts) {
    // Get the current post ID
    $post_ID = get_the_ID();

    // Check if the current post has backlinks
    $backlinks = get_post_meta($post_ID, '_backlinks', true);
    if (empty($backlinks)) {
        return ''; // No backlinks found, return empty string
    }

    // Prepare the output string
    $output = '<style>ul.referring-posts li::after { content: ", "; } ul.referring-posts li:last-child::after { content: ""; } ul.referring-posts li:last-child::before { content: "and "; }ul.referring-posts li:first-child::before { content: none; }</style>';
    $output .= '<div class="wp-block-group has-primary-color has-text-color has-small-font-size">';
    $output .= '<p style="display: inline;">Referring posts: </p>';
    $output .= '<ul class="referring-posts" style="display: inline; list-style-type: none; padding-left: 0;">';

    // Retrieve the backlinked posts and sort them by date
    $backlinked_posts = get_posts(array(
        'post__in' => $backlinks,
        'orderby'  => 'post_date',
        'order'    => 'ASC',
		'numberposts' => -1
    ));

    // Loop through each backlinked post and generate the list items
    foreach ($backlinked_posts as $backlinked_post) {
        // Get the linked post title and URL
        $backlink_title = $backlinked_post->post_title;
        $backlink_url   = get_permalink($backlinked_post);

        // Add the list item to the output string
        $output .= '<li class="referring-post" style="display: inline; padding-left: 0;"><a href="' . $backlink_url . '">' . $backlink_title . '</a></li>';
    }

    $output .= '</ul>';
    $output .= '</div>';

    return $output;
}
add_shortcode('display_backlinks', 'display_backlinks_shortcode');