-1

I want to create a shortcode for putting newsletter opt-in boxes in my posts and pages. But depending on the page or post, I want to have different headline and description for the opt-in box.

I created a shortcode-newsletter.php file with this code in it:

<?php

function newsletter(){

return <<<HTML

    <div class="newsletterForm">

        <h3>Newsletter Box Headline</h3>

        <p>Newsletter Box Description</p>

        <form method="post" action="https://domain.com/newsletter/z2o7q6">

            <input type="hidden" name="ml-submit" value="1">

                <div class="newsletterFields">

                    <div class="newsletterEmail">

                        <input required="" type="email" class="newsletterInput" name="fields[email]"
                            placeholder="Your email...">
                    </div>

                    <div class="newsletterButton">

                        <input type="submit" class="newsletterSubmit" value="Subscribe">

                    </div>

                </div>

                <div class="newsletterDisclaimer">

                    <p>Newsletter Box Disclaimer</p>

            </div>

        </form>

    </div>
HTML;
}
?>

In functions.php I added:

include('shortcode-newsletter.php');
add_shortcode( 'newsletter', 'newsletter' );

Now I want to have a shortcode with custom parameters:

[newsletter url="formActionUrl" headline="newsletterHeadline" description="newsletterDescription"]

But I don't know how to change the first code to have those parameters customizable.

Thank you for your help!

0

As per the shortcode documentation, your shortcode callback recieves any parameters set by the user in a $atts variable. You can combine them with any default values you might have with shortcode_atts().

function newsletter( $atts ) {

  $atts = shortcode_atts( 
    array(
      'url'         => 'https://domain.com/newsletter/z2o7q6', // change default value as needed
      'headline'    => 'Newsletter Box Headline', // change default value as needed
      'description' => 'Newsletter Box Description', // change default value as needed
    ), 
    $atts, 
    'newsletter' 
  );

  // you can access parameters with $atts['url'], $atts['headline'], and $atts['description']
  // e.g <h3><?php echo esc_html($atts['headline']); ?></h3>

}

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.