0
0
Wordpressframework~5 mins

Hook priority and arguments in Wordpress

Choose your learning style9 modes available
Introduction

Hooks let you change how WordPress works without changing its core. Priority and arguments help control when and how your code runs with hooks.

You want to run your code before or after other code hooked to the same action or filter.
You need to pass extra information to your hooked function.
You want to make sure your code runs in a specific order among many hooked functions.
Syntax
Wordpress
add_action('hook_name', 'your_function', priority, accepted_args);

// priority is a number (default 10)
// accepted_args is how many arguments your function accepts (default 1)

Lower priority numbers run first. Default is 10.

accepted_args tells WordPress how many arguments to pass to your function.

Examples
Runs my_init_function on 'init' hook with default priority 10 and 1 argument.
Wordpress
add_action('init', 'my_init_function');
Runs my_init_function earlier because priority is 5 (lower than default 10).
Wordpress
add_action('init', 'my_init_function', 5);
Runs my_save_function on 'save_post' hook with default priority 10 and accepts 2 arguments.
Wordpress
add_action('save_post', 'my_save_function', 10, 2);
Sample Program

This example hooks two functions to the same 'wp_footer' action. The function with priority 10 runs before the one with priority 20.

Wordpress
<?php
function first_function() {
    echo "First function runs\n";
}

function second_function() {
    echo "Second function runs\n";
}

add_action('wp_footer', 'second_function', 20);
add_action('wp_footer', 'first_function', 10);

// When WordPress runs 'wp_footer' hook, first_function runs before second_function because it has lower priority.
?>
OutputSuccess
Important Notes

If two functions have the same priority, they run in the order they were added.

Make sure your function accepts the number of arguments you specify, or you may get errors.

Summary

Hooks let you add or change WordPress behavior.

Priority controls the order functions run on the same hook.

Accepted arguments tell WordPress how many values to pass to your function.