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

function track_internal_backlinks($new_status, $old_status, $post) {
    // Check if the post is transitioning to 'publish'
    if (($new_status === 'publish' && $old_status !== 'publish') || ($new_status === 'publish' && $old_status == 'publish')) {
        $post_ID = $post->ID;
        $linked_posts = array();

        // Get the content of the current post
        $post_content = get_post_field('post_content', $post_ID);

        // Find all internal links within the post content
        preg_match_all('/<a\s+.*?href=["\'](?:https?:\/\/)?(?:www\.)?bix\.blog(.*?)["\'].*?>/', $post_content, $matches);

        if (!empty($matches[1])) {
            foreach ($matches[1] as $link) {
                // Get the linked post ID
                $linked_post = url_to_postid($link);

                if ($linked_post !== 0) {
                    // Add the linked post ID to the array if it's not already present
                    if (!in_array($linked_post, $linked_posts)) {
                        $linked_posts[] = $linked_post;

                        // Track the current post as a backlink in the linked post's meta
                        $backlinks = get_post_meta($linked_post, '_backlinks', true);
                        if (empty($backlinks)) {
                            $backlinks = array($post_ID);
                        } elseif (!in_array($post_ID, $backlinks)) {
                            $backlinks[] = $post_ID;
                        }
                        update_post_meta($linked_post, '_backlinks', $backlinks);
                    }
                }
            }
        }

        // Save the linked posts in the current post's meta
        update_post_meta($post_ID, '_linked_posts', $linked_posts);
    } elseif ($old_status === 'publish' && $new_status !== 'publish') {
        // Post is transitioning from 'publish' to another status
        $post_ID = $post->ID;

        // Get the linked posts meta for the current post
        $linked_posts = get_post_meta($post_ID, '_linked_posts', true);

        // Remove backlinks from the linked posts
        if (!empty($linked_posts)) {
            foreach ($linked_posts as $linked_post) {
                $backlinks = get_post_meta($linked_post, '_backlinks', true);

                if (!empty($backlinks)) {
                    // Remove the current post ID from the backlinks if it's present
                    $backlinks = array_diff($backlinks, array($post_ID));
                    update_post_meta($linked_post, '_backlinks', $backlinks);
                }
            }
        }

        // Remove the linked posts meta from the current post
        delete_post_meta($post_ID, '_linked_posts');
    }
}
add_action('transition_post_status', 'track_internal_backlinks', 10, 3);