I want to create a route in my wordpress plugin that isn’t linked to a page but to an action that sends an email. So i would send a get request like this
example.com/send/email?email=test@test.co.uk
and this would link to an action with the email as a parameter. I’m very new to WordPress so forgive me if this is a stupid question but I’m really struggling to achieve this or evebn find a good starting point, can anyone help?
A good option in your case would be to use a rewrite endpoint. A rewrite endpoint allows you to add extra query parameters to certain URLs. For instance you can add a
gallery
endpoint to all posts, that could render a different template showing all images for the given post. More information aboutadd_rewrite_endpoint()
can be seen in the Codex.Below is some code that adds a
send
endpoint toEP_ROOT
(the home page of the site). Note that you’ll have to go toSettings > Permalinks
after adding this code in order for the rewrite endpoint to start working.Once we have the rewrite endpoint in place, we hook to the
template_redirect
action in order to check for the presence of thesend
query var. Ifsend
is not present, then we do nothing.If
send
is present, but empty(like for instance if you load the pagehttp://example.com/send/
), then we redirect to the home page.Otherwise we split
send
into multiple parts at every/
and assign that to the$send_parts
variable. We then use aswitch
statement to see what the$send_action
(the first part after/send/
) and act accordingly.Right now we’re only checking for the
email
action(if it’s not email, we redirect to the home page again). We check if there’s an actual email($send_parts[1]
) and whether it’s a valid email(I have to note thatis_email()
is not RFC compliant and it might reject valid email addresses, so use with caution). If it’s a valid email, we usewp_mail()
to send the email, otherwise we redirect to the home page.Now, since I don’t know how you’re planning to implement this my code doesn’t cover things like authentication(who can send emails – if it’s everyone, I can abuse your site and spam users and get your mail server blacklisted – bad 🙁 ), generation of the email Subject and Message(is it going to be dynamic via
$_POST
variables, is it going to be pre-defined, etc.). Those are specifics that you will have to implement on your own.Once the code below is placed in an appropriate file(a .php file that gets loaded in the current theme, or an active plugin’s file) and you regenerate your Rewrite Rules(by going to
Settings > Permalinks
), you can go to http://example.com/send/email/your.email@example.com/ and you should receive an email with a subject “Hello” and a message “This is a message”.