One of the keys to the success of WordPress is its ability to extend on the basis that offers us as standard, ie, to do anything we can imagine from its "standard" structure.
If you notice, a plugin that adds a new functionality to WordPress is nothing more than an extension of a file: functions.php. A file that we find in the root folder of each theme.
In this file we find the basic functions for a website to work but what happens if we want to add more features to our website?
Luckily, there are many plugins and snippets that allow us to extend and customize any element, but there is always a warning if you want to add a snippet and you do it in the functions.php file: "If you change theme, you will lose those changes". This happens because when you change theme, the active functions.php file becomes the one of the new theme.
That's why it's important that the custom functions we add through snippets are placed, in most cases, in one or more plugins with independent functionalities, as long as those functions are not directly linked to the theme we use.
How do I create my functionality plugin
It's simple, just create a file with the PHP extension. Ideally, you should start it with the following header, customized to your liking, of course.
From my experience I've learned that in order not to confuse you, the best thing to do is to include an index with the snippets you are adding, this will give you an idea at a glance of what you have in your functionality plugin. I do it this way:
And from the last element of this index you can add the snippets you are going to use.
In my case there are a number of functions that I use on most websites and others that I use depending on what I want to customize on that website.
I leave you the file of functionalities that I consider basic and that I usually add to all the websites I work with. Feel free to delete the functions that you do not need or add the ones you want:
hay que poner el dominio de tu web sin protocolo http://)
function cmdh_dns_prefetch() {
echo '
';
}
add_action('wp_head', 'cmdh_dns_prefetch', 0);
// Desactivar las etiquetas meta robots duplicadas (A partir de WordPress 5.7
remove_filter( 'wp_robots', 'wp_robots_max_image_preview_large' );
// Mostrar un aviso en el admin bar si no se está indexando el sitio
add_action('admin_bar_menu', 'cmdh_site_indexation_warning', 999);
function cmdh_site_indexation_warning($bar) {
if (get_option('blog_public') == 0) {
$icon = '"\f530"';
$icon_color = 'red';
}
echo
'';
$bar->add_menu(
[
'id' => 'site-indexation-warning',
'title' => '',
'href' => '/wp-admin/options-reading.php',
'meta' => [
'target' => '_self',
'title' => '¡Cuidado! la opción «Disuadir a los motores de búsqueda de indexar este sitio» está activada',
],
]);
}
// Eliminar elementos del menú de un plugin del admin bar (barra superior)
add_action( 'wp_before_admin_bar_render', 'cmdh_remove_admin_bar_menu_items', 999 );
function cmdh_remove_admin_bar_menu_items() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu( 'updraft_admin_node' ); // Eliminar menú de UpdraftPlus
$wp_admin_bar->remove_menu( 'gform-forms' ); // Eliminar menú de Gravity Forms
$wp_admin_bar->remove_menu( 'SG_CachePress_Supercacher_Purge' ); // Eliminar menú Purgar caché de SiteGround
}
// Ocultar la opción de actualizar automáticamente los plugins menos al usuario con ID = xxx (carlosmdh)
add_action( 'init', 'cmdh_disable_plugin_auto_update_ui' );
function cmdh_disable_plugin_auto_update_ui () {
$user_id = get_current_user_id();
if ( ! $user_id === xxx) { // Agregar el ID del usuario al que deseas permitir gestionar las actualizaciones automáticas de plugins
return;
} else {
add_filter( 'plugins_auto_update_enabled', '__return_false' );
}
}
// Deshabilitar el email de actualizaciones automáticas de plugins
add_filter( 'auto_plugin_update_send_email', '__return_false' );
// Deshabilitar el email de actualizaciones automáticas de temas
add_filter( 'auto_theme_update_send_email', '__return_false' );
// Definir la estructura de los permalinks por defecto a nombre del post
function set_permalink(){
global $wp_rewrite;
$wp_rewrite->set_permalink_structure('/%postname%/');
}
add_action('init', 'set_permalink');
// Deshabilitar el JavaScript para responder comentarios
function clean_header(){ wp_deregister_script( 'comment-reply' ); } add_action('init','clean_header');
// Dar soporte a la altura de línea personalizada en el editor
add_theme_support( 'custom-line-height' );
// Dar soporte unidades personalizadas
add_theme_support( 'custom-units', 'rem', 'em' );
// Dar de baja los patrones de bloques por defecto de WordPress (desde WordPress 5.5)
add_action( 'init', 'cmdh_unregister_block_patterns' );
function cmdh_unregister_block_patterns(){
$block_patterns = array (
'core/two-buttons', // Patrón «Dos botones»
'core/three-buttons', // Patrón «Tres botones»
'core/text-two-columns', // Patrón «Dos columnas de texto»
'core/text-two-columns-with-images', // Patrón «Dos columnas de texto con imágenes»
'core/text-three-columns-buttons', // Patrón «Tres columnas de texto con botones»
'core/two-images', // Patrón «Dos imágenes contiguas»
'core/large-header', // Patrón «Cabecera grande con un encabezado»
'core/large-header-button', // Patrón «Cabecera grande con un encabezado y un botón»
'core/heading-paragraph', // Patrón «Encabezado y párrafo»
'core/quote' // Patrón «Cita»
);
foreach ($block_patterns as $bp ):
unregister_block_pattern( $bp );
endforeach;
}
// Dar de baja las categorías de patrones de bloques por defecto de WordPress (desde WordPress 5.5)
add_action( 'init', 'cmdh_unregister_block_patterns_categories' );
function cmdh_unregister_block_patterns_categories(){
$block_patterns_categories = array(
'buttons', // Categoria «Botones» de los patrones de bloques
'columns', // Categoria «Columnas» de los patrones de bloques
'gallery', // Categoria «Galeria» de los patrones de bloques
'header', // Categoria «Cabeceras» de los patrones de bloques
'text' // Categoria «Texto» de los patrones de bloques
);
foreach ($block_patterns_categories as $bpc ):
unregister_block_pattern_category ( $bpc );
endforeach;
}
/* Registrar un patrón de bloques (es un ejemplo, para que podáis ver como hacerlo)
Para ver cómo crear el código del patrón de bloque que aparece tras ´content.=>, revisa el post de
Fernando Tellado en la siguiente url: https://ayudawp.com/como-crear-patrones-de-bloques/ */
add_action( 'init', 'cmdh_register_block_patterns' );
function cmdh_register_block_patterns() {
register_block_pattern(
'nombre-principal',
array(
'title' => __( 'Noticias', '' ),
'description' => _x( 'Patron para poner el contenedor principal un Título H2 y un parrafo', 'Block pattern description', 'nombre-de-categoria' ),
'categories' => array( 'Nombre categoría personalizada AQUI' ),
'content' => "\n\nEncabezado
\n\n\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae euismod elit. Phasellus eu justo consectetur, consectetur tortor et, sodales sem. Vivamus dapibus lorem sit amet congue finibus. Donec interdum placerat dolor, ut aliquet urna congue nec. Sed tristique arcu non dolor sodales pulvinar. Cras auctor ligula ac commodo vehicula. Ut malesuada mattis diam id faucibus. Ut non erat in ligula pharetra commodo id ut metus. Maecenas pellentesque est at neque ultrices cursus rutrum sit amet purus. Nam vitae nibh non metus sagittis porta.
\n\n\n\n
Sed auctor, lacus at pretium pellentesque, dui orci ultricies augue, ac tincidunt sem ligula dapibus felis. Etiam in dolor sit amet ex elementum consectetur non eu arcu. Vivamus et nisi eget orci sagittis tristique vel et nulla. Duis viverra pulvinar magna, id ultricies erat molestie sit amet. Donec malesuada odio vel leo porttitor rhoncus. Sed ut libero mollis, laoreet ligula vitae, faucibus diam. Suspendisse volutpat neque vitae erat gravida, eget convallis massa porttitor. Praesent lobortis posuere sapien, a interdum nisl eleifend ut. Nunc id ornare dolor.
\n\n",
)
);
}
// Añadir una categoría personalizada a los patrones de bloques
register_block_pattern_category(
'Nombre categoría personalizada AQUI',
array( 'label' => __( 'Nombre categoría personalizada AQUI', 'text-domain' ) )
);
?>
Where do I place the functionality plugin?
Once you have created your functionality plugin you have two options;
- Use it as a conventional plugin.
- Use it as a must-have plugin.
In the first case, what you should do is create a folder inside the plugins folder in wp-content and upload the file there. With that in your list of plugins you will see a new one with the name you have put in the header (in my case it would be "Customizations carlosmdh". Be careful, you will have a plugin that will do everything you add but it can be deactivated.
That's why, in my case, I prefer to add it as a must-have plugin. To do this, what I do is to upload it via FTP to the mu-plugins folder that is also inside wp-content. In case that folder doesn't exist, you can create it without fear.
This guarantees that the functions you add to this file will be executed and that the functionality plugin will not be deactivated by accident. If you want to deactivate a feature you have added, you can delete or comment out the code and if you want to completely deactivate the plugin, you will have to delete or comment it out completely.
One last piece of advice
This applies to this case as well as any code (php, css or JavaScript) that you add, ADD COMMENTS, that is, document what each function does and, if any, document the options that could be there, in case in the future you need to change something or you are going to pass that code to someone else. In the code example I have left you will see that there are quite a few comments.
Don't go yet
I invite you to leave me your impressions and / or questions in the Contact Form And that I propose new topics that you would like to try in these tutorials. I Will Be happy to answer by email and write on this blog.