0

Is it possible to put a function somewhere other than the functions.php file? I.e directly into a template?

I have the following that needs to be called before some code and to make sure this happens I want to place it above everything else in the template:

function set_region_cookie()
{
    if(isset($_POST['region']))
    {
        // Set Cookie
        setcookie('region', $_POST['region'], time()+1209600);
        // Reload the current page so that the cookie is sent with the request
        header('Region: '.$_SERVER['REQUEST_URI']);
    }
}
add_action('init', 'set_region_cookie');

2 Answers 2

2

Since you are using init "add_action", then it is best not to use it in a template - since "add_action" is used by Wordpress core's "do_action" - which comes before the templates.

If you want this function to take higher priority, place it in functions.php but use the 'priority' variable of "add_action":

add_action( $tag, $function_to_add, $priority );

The default priority is 10. See more here

Alternatively, if this is relevant only for a specific template, then I don't think you need add_action at all - or even a function for that matter.

Simply place the inner code of your function BEFORE get_header() in your template:

if(isset($_POST['region']))
{
    // Set Cookie
    setcookie('region', $_POST['region'], time()+1209600);
    // Reload the current page so that the cookie is sent with the request
    header('Region: '.$_SERVER['REQUEST_URI']);
}
-1

Yes, you can put function in anywhere in template. But, that function used for that template only.

1
  • That doesn't work for functions that are hooked to a hook that did run previously. Hooking into init for a function placed inside a template is not possible.
    – kaiser
    Commented Oct 1, 2012 at 15:04

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.