I try to use the hook wp_head on a template page but this does not work

add_action('wp_head', 'to_head');

function to_head(){
    //do stuff

I placed this code on a template part what is called by get_template_part( 'temp-parts/content/pages/catalog' );

Can you use the hook only on the functions.php or is there a way to use this on any page

  • You can use the hook in any templates as long as the function or hook named wp_head has not yet been called - in templates other than header.php, your code would be placed before get_header().
    – Sally CJ
    Commented Apr 2, 2021 at 19:55

2 Answers 2


As Sally CJ noted in a comment, if you're adding the add_action(), which targets wp_head in a partial file, you add with get_template_part() then you're late as the action has already fired.

You need to use add_action() in your functions.php file to register your callback before the target action is fired. If you need to add the callback only on certain context, then use the conditional tags to check what is the current template / content.

// Do something on every template/view
add_action('wp_head', 'my_global_head_function');

add_action('template_redirect', 'my_template_redirect_callback');
function my_template_redirect_callback() {
    // Only pages
    if ( is_page() ) {
        add_action('wp_head', 'my_page_head_function');

function my_global_head_function() {
    echo 'This works everywhere';

function my_page_head_function() {
    echo 'This is a page';

Why not simply create a function, add the action then do the action?

function code_name() {
    // add code here
add_action( 'action_name', 'code_name' );

Then inside your template file, simply paste <?php do_action( 'action_name' ); ?>

P.S. You may change the action_name and code_name to whatever you like!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.