Video Tutorial Actions


In this chapter we will discuss a first key point of WordPress: Hooks. These hooks allow you to extend WordPress from a theme or a plugin by injecting functionality at key moments.

Operation

To add an operation to perform when executing a hook, you just need to use the do_action () function. In the case of a theme, the hooks will be defined in the file functions.php but you are free to organize them as you see fit.

function montheme_register_assets ()
{
    wp_register_style ('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css', ());
    wp_register_script ('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js', ('popper', 'jquery'), false, true);
    wp_register_script ('popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js', (), false, true);
    wp_deregister_script ('jquery');
    wp_register_script ('jquery', 'https://code.jquery.com/jquery-3.2.1.slim.min.js', (), false, true);
    wp_enqueue_style ('bootstrap');
    wp_enqueue_script ('bootstrap');
}
add_action ('wp_enqueue_scripts', 'montheme_register_assets');

The action wp_enqueue_scripts allows for example to save new javascript or css elements to load. You can learn more about the order in which actions are executed by going to this documentation page. All hooks are listed in the Code Reference section of the documentation.

You can also pass a third parameter to define the "priority" of your action. This allows WordPress to know in what order to launch the different actions. Finally the 4th argument allows to specify the number of arguments expected by the callback method.

Another interesting hook is the hook after_setup_theme which will allow you to record information about how your theme works.

function montheme_supports ()
{
    add_theme_support ('title-tag');
    add_theme_support ('post-thumbnails');
    add_theme_support ('menus');
    register_nav_menu ('header', 'At the top of the menu');
    register_nav_menu ('footer', 'Footer');

    add_image_size ('post-thumbnail', 350, 215, true);
}
add_action ('after_setup_theme', 'montheme_supports');