In case this helps, I tried making the following changes to the code:
In the save_custom_body_class_post_meta_boxes function, I added the $post_id parameter and sanitized the input using sanitize_text_field to prevent XSS.
In the add_custom_body_class_box function, I used esc_attr to escape the value when displaying it in the input field.
In the add_custom_field_body_class function, I used esc_attr to escape the custom body class before adding it to the classes array.
I think these changes should help prevent the stored XSS vulnerability in the plugin, but I’m not 100% sure:
<?php
/**
* Plugin Name: Add Custom Body Class
* Author: Anil Ankola
* Version: 1.4.1
* Description: Use this plugin to add a custom class in the HTML body tag.
* Text Domain: add-custom-body-class
*/
if (!defined('ABSPATH')) exit; // Prevent Direct Browsing
// Add Custom meta box
function add_custom_body_class_post_meta_boxes()
{
$screens = get_post_types();
foreach ($screens as $screen) {
add_meta_box('add_custom_body_class_box', 'Add Custom Body Class', 'add_custom_body_class_box', $screen, 'side', 'default');
}
}
add_action("admin_init", "add_custom_body_class_post_meta_boxes");
function save_custom_body_class_post_meta_boxes($post_id)
{
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (get_post_status($post_id) === 'auto-draft') {
return;
}
// Sanitize the input
$custom_body_class = sanitize_text_field($_POST["add_custom_body_class"]);
update_post_meta($post_id, "add_custom_body_class", $custom_body_class);
}
add_action('save_post', 'save_custom_body_class_post_meta_boxes');
function add_custom_body_class_box($post)
{
$get_class_value = get_post_custom($post->ID);
// Initialize the value with an empty string
$add_custom_body_class = '';
if (isset($get_class_value['add_custom_body_class'][0])) {
$add_custom_body_class = $get_class_value['add_custom_body_class'][0];
}
?>
<input type="text" id="add_custom_body_class" name="add_custom_body_class" value="<?php echo esc_attr($add_custom_body_class); ?>">
<?php
}
// Display body class function
add_filter('body_class', 'add_custom_field_body_class');
function add_custom_field_body_class($classes)
{
if (function_exists('is_shop') && is_shop()) {
$post_id = get_option('woocommerce_shop_page_id');
} elseif (is_home()) {
$post_id = get_option('page_for_posts');
} else {
$post_id = get_the_ID();
}
// Get the custom body class and escape it
$show_body_class = get_post_meta($post_id, 'add_custom_body_class', true);
if ($show_body_class) {
$classes[] = esc_attr($show_body_class);
}
// Return the $classes array
return $classes;
}