Custom Newsletter Form
Advanced snippet for adding a custom newsletter form to your WordPress site
<?php
// Create a shortcode to display the newsletter form
function custom_newsletter_form_shortcode() {
ob_start();
?>
<form id="newsletter-form" method="post">
<label for="newsletter-name">Name:</label>
<input type="text" name="newsletter_name" id="newsletter-name" required />
<label for="newsletter-email">Email:</label>
<input type="email" name="newsletter_email" id="newsletter-email" required />
<input type="submit" name="newsletter_submit" value="Subscribe" />
</form>
<?php
return ob_get_clean();
}
add_shortcode('newsletter_form', 'custom_newsletter_form_shortcode');
// Handle form submission
function handle_newsletter_form_submission() {
if (isset($_POST['newsletter_submit'])) {
// Sanitize input data
$name = sanitize_text_field($_POST['newsletter_name']);
$email = sanitize_email($_POST['newsletter_email']);
// Validate email
if (!is_email($email)) {
echo '<p class="error">Invalid email address.</p>';
return;
}
// Prepare email content
$to = get_option('admin_email');
$subject = 'New Newsletter Subscription';
$message = "Name: $name\nEmail: $email";
$headers = array('Content-Type: text/plain; charset=UTF-8');
// Send email
wp_mail($to, $subject, $message, $headers);
// Display a success message
echo '<p class="success">Thank you for subscribing to our newsletter!</p>';
}
}
add_action('wp_footer', 'handle_newsletter_form_submission');
?>
Post Comment