Jason
Jason

Reputation: 1141

Wordpress shortcode outside <p> tags

This might be a simple ask but I have a shortcode that pulls the url parameters. It then wraps those in HTML tags and returns. The problem I have is when the client puts the shortcode inside the wordpress editor and centers it the returned values on the page are left aligned. When I inspect the element I see the returned values outside the original centered <p> tags.

<p style="text-align: center;"></p>
<h2>Thank You for Your Request</h2>
<p>We will be in touch shortly to schedule your briefing</p>
<p></p>

here is the function:

add_shortcode('return-url-params', 'get_params');

function get_params() {

    $str = '';
    $str .= '<h2>' . $_GET['thxheadline'] . '</h2>';
    $str .= '<p>' . $_GET['thxtext'] . '</p>';

   return urldecode($str);

}

How can I return the shortcode's values inside the centered

tags?

Upvotes: 3

Views: 1049

Answers (2)

George
George

Reputation: 36784

The issue here is that WordPress wraps your shortcode in a paragraph tag in order to centrally align your shortcode.

This means that on the page, your <h2> and <p> elements are children of said paragraph, which is invalid markup. Now your page is parsed incorrectly by the browser and results in what you see when you inspect the element. (Note that if you were to look in the page source, you'd see the invalid markup).

Your best option would be to provide your client with the capability of changing the alignment by means of a shortcode parameter. If your shortcode function looked like the following:

add_shortcode('return-url-params', 'get_params');

function get_params( $atts ) {

    $atts = shortcode_atts( array(
        'align' => 'inherit',
    ), $atts, 'return-url-params' );

    $str = '';
    $str .= '<div style="text-align: ' . $atts['align'] . '">';
    $str .= '<h2>' . $_GET['thxheadline'] . '</h2>';
    $str .= '<p>' . $_GET['thxtext'] . '</p>';
    $str .= '</div>';

    return urldecode($str);

}

Then your client could use the shortcode like so:

[return-url-params align="center"]

With the 'align' parameter taking any CSS text-align property.

You could also use the parameter to give the containing <div> a specific CSS class and apply styles to that, but this is just to give you an idea.

Upvotes: 2

milan kyada
milan kyada

Reputation: 579

It will append paragraph tag every time because you can't use header tag inside the paragraph tag. You can achieve your desired result by below code.

add_shortcode('return-url-params', 'get_params');

function get_params() {

    $str = '<div style="text-align: center;">';
    $str .= '<h2>Header</h2>';
    $str .= '<p>paragraph</p>';
    $str .= '</div>';
   return urldecode($str);

}

Upvotes: 0

Related Questions