Skip to content

Instantly share code, notes, and snippets.

@ohryan
Last active February 28, 2024 19:15
Show Gist options
  • Save ohryan/c5801500917fadc153fd6572cc59b0c9 to your computer and use it in GitHub Desktop.
Save ohryan/c5801500917fadc153fd6572cc59b0c9 to your computer and use it in GitHub Desktop.
<?php
/**
Plugin Name: AI Bot Blocker
Description: Adds an option to the Reading settings to block AI bots via robots.txt.
Version: 1.0
Author: Ryan Neudorf
Author URI: https://ohryan.ca/
*/
function aibotblocker_settings_init()
{
add_settings_field(
'aibotblocker_block_bots', // ID
'Block AI Bots', // Title
'aibotblocker_settings_field_callback', // Callback
'reading', // Page
'default' // Section
);
register_setting('reading', 'aibotblocker_block_bots');
}
function aibotblocker_settings_field_callback()
{
$value = get_option('aibotblocker_block_bots', 0);
echo '<label for="aibotblocker_block_bots"><input type="checkbox" id="aibotblocker_block_bots" name="aibotblocker_block_bots" value="1" ' . checked(1, $value, false) . '/> '.__('Discourage AI training bots from scanning your site').'</label>';
}
add_action('admin_init', 'aibotblocker_settings_init');
function aibotblocker_filter_robots_txt($output, $public)
{
$block_bots = get_option('aibotblocker_block_bots', 0);
if ($block_bots) {
$output .= "\nUser-agent: GPTBot\n";
$output .= "Disallow: /\n";
}
return $output;
}
add_filter('robots_txt', 'aibotblocker_filter_robots_txt', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment