Home / Admin / Prevent Publishing Posts with Broken Internal Links
Duplicate Snippet

Embed Snippet on Your Site

Prevent Publishing Posts with Broken Internal Links

Checks all internal links within post content before publishing. If a linked page or post returns a 404 status, publishing is blocked and the post is reverted to Draft.

Installation:
Add this snippet as a PHP Snippet in WPCode and set it to Auto Insert → Run Everywhere.

Note:
For performance reasons, this check only runs when a post is being published.

Code Preview
php
<?php
<?php
/**
 * Snippet: Prevent Publishing Posts with Broken Internal Links
 * Description: Stops publishing when broken internal links are detected inside content.
 *
 * Curated by: Avijit Datta
 * Agency: CypraWeb Digital
 * Website: https://cyprawebdigital.com
 *
 * Version: 1.0
 */
add_action('transition_post_status', 'cwd_check_internal_links_before_publish', 10, 3);
function cwd_check_internal_links_before_publish($new_status, $old_status, $post) {
    if ($new_status !== 'publish' || $old_status === 'publish') {
        return;
    }
    if (wp_is_post_revision($post->ID)) {
        return;
    }
    preg_match_all(
        '/<a\s[^>]*href=[\"\']([^\"\']+)[\"\']/i',
        $post->post_content,
        $matches
    );
    if (empty($matches[1])) {
        return;
    }
    $site_host = wp_parse_url(home_url(), PHP_URL_HOST);
    foreach ($matches[1] as $url) {
        $link_host = wp_parse_url($url, PHP_URL_HOST);
        if ($link_host && $link_host !== $site_host) {
            continue;
        }
        $response = wp_remote_head($url, array(
            'timeout' => 5,
            'redirection' => 3
        ));
        if (is_wp_error($response)) {
            continue;
        }
        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code == 404) {
            remove_action(
                'transition_post_status',
                'cwd_check_internal_links_before_publish',
                10
            );
            wp_update_post(array(
                'ID' => $post->ID,
                'post_status' => 'draft'
            ));
            add_filter('redirect_post_location', function($location) {
                return add_query_arg(
                    'cwd_broken_links',
                    1,
                    $location
                );
            });
            break;
        }
    }
}
add_action('admin_notices', function() {
    if (!isset($_GET['cwd_broken_links'])) {
        return;
    }
    echo '<div class="notice notice-error">';
    echo '<p><strong>Publishing blocked:</strong> Broken internal links were detected in the content. Please fix them before publishing.</p>';
    echo '</div>';
});

Comments

Add a Comment