In my plugin if I hard code an email address in my function with either wp_mail()
or mail()
I can get my form to work:
function email_form($ip_address, $agent, $referrer, $email, $name, $message) {
$to = "[email protected]";
$subject = "Hard Coded";
$email_body =
"IP ADDRESS: " . $ip_address . "\n" .
"USER AGENT: " . $agent . "\n\n" .
"EMAIL: " . $email . "\n" .
"NAME: " . $name . "\n" .
"MESSAGE: " . $message . "\n";
mail("$to", "$subject", "$email_body", "From: $email");
}
However, when I try to add the email based on the author with:
$to = get_the_author_meta('user_email');
from a global $post;
it will not send the email.
If I build a function at the beginning of the template and set a variable I can get the author to fire but I think this approach is incorrect. I can build a setting page but I want the recipient to be the author of the page.
In a page template that sends the processing to another PHP file what is the proper way to pass the author's email of the page post type or any other WP related data (the_title()
, theme, etc. etc) through WP_REST_Request
?
EDIT:
After finding out I should go wp_localize_script
I authored:
function foobar() {
if (is_page_template('page-foo.php')) {
wp_enqueue_script( 'bar_js', site_url() . '/js/bar.js', array('jquery'), '1.0.0', true);
$localized = array(
'url_string' => site_url(),
'form_id' => get_the_ID(),
'author_email' => get_the_author_meta('user_email', get_post_field('post_author', get_the_ID())),
);
wp_localize_script('bar_js', 'form_object', $localized);
};
}
add_action('wp_enqueue_scripts', 'foobar');
and passed in bar.js
:
jQuery(document).ready(function($) {
console.log('file is being detected'); // FOR TESTING
console.log(form_object.author_email);
});
but is there a better way to call the author email outside of the loop in this manner?