0

I'm new to developing with WordPress. I read here that a good way to process data posted from forms is to insert an action on the init function like so:

add_action( 'init', 'contact_form_send_email' );

My function seems to be processing the data correctly, but I can't figure out how to make a variable available within the same template that has the form.

What is the way to do this? I've heard that setting global variables is not a good way to go.

2

The difference between add_action() and add_filter() is semantic not technical, except that a filter expects a returned value and an action does/will not. The question is whether contact_form_send_email() needs to be called-at /hooked-to init.

If not, you can define your filter in the template with apply_filters(), and then hook to it to run your function and return a value to it.

In template page:

$some_variable = 'some value';
$some_variable = apply_filters('my_filter_hook', $some_variable);

In functions.php

add_filter('my_filter_hook', 'contact_form_send_email', 10, 1 );

function contact_form_send_email( $some_variable ) {
    //do stuff
    $some_variable = 'some new value';

    return $some_variable;

}

To help determine where you need to hook, this Actions Reference can be useful. Scroll down and you will see some template specific hooks as well.

  • Thanks for this, it seems like what I was looking for, let me come back to this once I've had a chance to digest. Cheers – goose Jul 30 '17 at 20:58
  • This is what I was looking for and you're right that I didn't need to hook into init. I'm still a little confused by the second argument of apply_filters, my function is picking up the $_POST array and I don't want to send anything, so I just inserted a 1 in this argument. It works, but still feels a bit un-natural. Do you have any suggestions? I can post full code somewhere if need be, perhaps on a separate question. – goose Jul 31 '17 at 19:29
0

There's an interesting feature in the WordPress that you might find it useful in situations like this. It's the ability to add something into the cache and retrieve it later.

Since you are hooking into the init, you can retrieve your cache afterward. This is done by using the wp_cache_add() function:

wp_cache_add( $key, $data, $group, $expire );

Add whatever data you wish, and then fetch them on your template:

wp_cache_get( $key, $group );

You can also delete the cache afterward if you wish. Take a look at this codex page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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