Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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');
share|improve this question

2 Answers 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']);
}
share|improve this answer

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

share|improve this answer
    
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 Oct 1 '12 at 15:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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