0
0
WordpressConceptBeginner · 3 min read

What Is Priority in Hooks in WordPress: Simple Explanation

In WordPress, priority is a number that controls the order in which functions hooked to the same action or filter run. Lower priority numbers run first, and higher numbers run later. This helps manage when your code executes relative to others.
⚙️

How It Works

Think of WordPress hooks like a to-do list where multiple people add tasks. The priority is like the order number assigned to each task. Tasks with smaller numbers get done first, and bigger numbers wait their turn.

When you add a function to a hook, you can set its priority number. WordPress then runs all hooked functions in order from lowest to highest priority. If two functions have the same priority, WordPress runs them in the order they were added.

This system helps you control when your code runs compared to other plugins or themes, avoiding conflicts and ensuring the right sequence.

💻

Example

This example shows two functions hooked to the same action with different priorities. The function with priority 5 runs before the one with priority 10.

php
<?php
function first_function() {
    echo 'First function runs.<br>';
}

function second_function() {
    echo 'Second function runs.<br>';
}

add_action('init', 'second_function', 10);
add_action('init', 'first_function', 5);
?>
Output
First function runs.<br>Second function runs.<br>
🎯

When to Use

Use priority when you want to control the order of your code execution with other hooked functions. For example, if your code depends on another plugin's setup, set a higher priority to run after it.

Common cases include modifying content filters, enqueueing scripts after others, or initializing features that rely on earlier actions.

Key Points

  • Priority is a number that sets the order of hooked functions.
  • Lower numbers run first; default priority is 10.
  • Functions with the same priority run in the order they were added.
  • Use priority to avoid conflicts and control execution flow.

Key Takeaways

Priority controls the order functions run on the same WordPress hook.
Lower priority numbers run before higher ones.
Default priority is 10 if not specified.
Use priority to manage dependencies and avoid conflicts.
Functions with the same priority run in the order they were added.