EDIT: Because of the answers below i changed the title and explanation for this question. Maybe there are other people who struggle with saftey questions, like me.
I am a beginner with Wordpress Plugins. I am trying to code a plugin for my customer projects, to add some features, that i nearly always use on every project.
My plugin creates an options page, where i can enable/disable my features with checkboxes.
I created a Feature to automatically add custom jQuery to Wordpress like this:
if( get_option('lwb_jquery') === 'on' ) {
function lwb_jquery() {
// Multisite Support
if( is_multisite()) {
$theme_dir = get_stylesheet_directory() . '/sites/' . get_current_blog_id();
if( !file_exists( $theme_dir )) {
mkdir( $theme_dir );
}
} else {
$theme_dir = get_stylesheet_directory(); // Pfad zum aktuellen Theme-Verzeichnis
}
// Pfade zu den zu erstellenden Ordnern und der Datei
$assets = $theme_dir . '/assets';
$subfolder = $assets . '/js';
$file_path = $subfolder . '/lwb-script.js';
// Überprüfe, ob der Ordner 'assets' existiert, falls nicht, erstelle ihn
if ( !file_exists( $assets )) {
mkdir( $assets );
}
// Überprüfe, ob der Ordner 'js' existiert, falls nicht, erstelle ihn
if ( !file_exists( $subfolder )) {
mkdir( $subfolder );
}
// Überprüfe, ob die Datei bereits existiert
if ( !file_exists( $file_path )) {
$file_content = '// Automatischer Inhalt in die neu erstellte Datei';
// Versuche, die Datei zu erstellen und den Inhalt zu schreiben
$result = file_put_contents( $file_path, $file_content );
}
}
add_action( 'admin_init', 'lwb_jquery' );
// Registrieren und einbinden der Javascript Datei
function lwb_jquery_script() {
// Multisite Support
if( is_multisite()) {
$url = get_stylesheet_directory_uri() . '/sites/' . get_current_blog_id() . '/assets/js/lwb-script.js';
wp_enqueue_script('lwb-script', $url, array('jquery'), '1.0', true);
} else {
wp_enqueue_script('lwb-script', get_stylesheet_directory_uri() . '/assets/js/lwb-script.js', array('jquery'), '1.0', true);
}
}
add_action('wp_enqueue_scripts', 'lwb_jquery_script');
This code snippet checks, if the feature is enabled. If its enabled, the file to put the custom jQuery code is created, and this file is registered in Wordpress with wp_enqueue_script()
So my question is: Is this a safe way to add my script with this feature?