如何做一个编辑robots.txt的功能?

WordPress模式是没有robots.txt真实文件的,但是请求域名+robots.txt会得到一个robots.txt的信息。如果要编辑这个文件,每次去服务器修改文件是比较麻烦,那就做一个编辑功能吧。

如何做一个编辑robots.txt的功能?
如何做一个编辑robots.txt的功能?

在你的WordPress主题functions.php中或者通过自定义代码的方式加入:

// Add menu item
function add_robots_menu_item() {
	add_submenu_page(
			'options-general.php', // Parent menu slug
			'Robots.txt Editor', // Page title
			'Robots.txt Editor', // Menu title
			'manage_options', // Capability required
			'robots-editor', // Menu slug
			'robots_editor_callback' // Callback function
	);
}
add_action('admin_menu', 'add_robots_menu_item');

// Callback function for menu page
function robots_editor_callback() {
	// Get the current robots.txt file content
	$robots_file = get_home_path() . 'robots.txt';
	$robots_content = file_get_contents($robots_file);

	// If the form has been submitted, save the new content
	if (isset($_POST['robots_content'])) {
			$new_content = stripslashes($_POST['robots_content']);
			file_put_contents($robots_file, $new_content);
			$robots_content = $new_content;
			echo '<div class="updated"><p>Robots.txt file updated.</p></div>';
	}

	// Display the form and the current content
	echo '<div class="wrap">';
	echo '<h1>Robots.txt Editor</h1>';
	echo '<form method="post"><table class="form-table"><tbody><tr><th scope="row">Current content<label></th><td><textarea rows="10" cols="100" readonly>' . esc_textarea($robots_content) . '</textarea></td></tr><tr><th scope="row">Edit content<label></th><td>';
	echo '<textarea name="robots_content" rows="10" cols="100">' . esc_textarea($robots_content) . '</textarea></td></tr></tbody></table>';
	echo '<p><input type="submit" class="button-primary" value="Save"></p>';
	echo '</form>';
	echo '</div>';
}

分类 WordPress技巧 本文由 清白之年 原创发布,转载请注明文章来源。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注