Problem

WordPress is an open source platform.

Thus, an average WordPress website includes code from different developers: themes, plugins, or other scripts.

Now, let’s say we have two different plugins from two different developers.

They both created a PHP function (not inside a PHP class) called init_plugin():

// Plugin A.
function init_plugin() {
    // Plugin A does something.
}

// Plugin B.
function init_plugin() {
    // Plugin B does something.
}

Once both plugins are activated, this will cause a conflict.

The same problem can happen with loading scripts and CSS files.

If both developers name the script the same - main:

// Plugin A.
wp_enqueue_script(
    'main',
    plugin_dir_url( __FILE__ ) . '/assets/js/main.min.js',
);

// Plugin B.
wp_enqueue_script(
    'main',
    plugin_dir_url( __FILE__ ) . '/assets/js/main.min.js',
);

This will also cause a conflict.

These conflicts can also happen between a plugin and a theme, or between a theme and WP core code for example.

This can cause an unwanted overwriting or even a fatal error.

Solution

As written in WordPress Best Practices: “Prefix Everything”.

WordPress developers should use a prefix when naming their functions, classes, global variables, hooks, script/style handles.

Using a unique identifier will prevent this type of conflicts with other developers’ code.

This is a simple rule to follow.

This prefix can simply be the name of the project or development brand, followed by an underscore (_) or a dash (-).

For instance, the prefix for this site could be notesontech.

So a function will be called notesontech_function_name, a class name will be NotesOnTech_Class_Name, and a script name will be notesontech-script-name.

Following on from the previous examples, the function names should now be:

// Plugin A.
function plugina_init_plugin() {
    // Plugin A does something.
}

// Plugin B.
function pluginb_init_plugin() {
    // Plugin B does something.
}

And the names of the scripts will be:

// Plugin A.
wp_enqueue_script(
    'plugina-main',
    plugin_dir_url( __FILE__ ) . '/assets/js/main.min.js',
);

// Plugin B.
wp_enqueue_script(
    'pluginb-main',
    plugin_dir_url( __FILE__ ) . '/assets/js/main.min.js',
);

References