0

I'm working with shortcodes in WordPress and I struggle with one problem. I'm trying to wrap my $content into tags, but it doesn't work properly. So here is my shortcode function:

<?php
add_shortcode('rect', 'pp_rect');
function pp_rect($atts, $content=null) {    
    extract(shortcode_atts(array(
        'x'     => 1,
        'y'    => 1,
        'url'       => false,
        'img'   => true,
    ), $atts));

    preg_match('@src="([^"]+)"@' , $content, $match);
    $img = array_pop($match);
    $content = preg_replace("/<img[^>]+\>/i", "", $content);

    if(!$img)
        $out = '<div class="rect rect-'.$x.'-'.$y.' no-img" style="background-image: url('.$img.');"><div class="rect-content">';
    else
        $out = '<div class="rect rect-'.$x.'-'.$y.' img" style="background-image: url('.$img.');"><div class="rect-content">';

    if ($url)
        $out .= '<a href="'.$url.'">'.do_shortcode($content).'</a></div></div>';
    else
        $out .= do_shortcode($content).'</div></div>';

    return $out;
}
?>

And if I'm trying to execute such a shortcode

[rect x=2 y=2 url=#]
<h1>Big header</h1>
<img src="someimg.jpg">
[/rect]

I'm receiving such an output:

<a href="#">
    <p></p>
    <h1>Big header</h1>
    <p></p>
</a>
<p>
    <a href="#"></a>
</p>

Instead of:

<a href="#">
    <h1>Big header</h1>
</a>

I'm staring at a code and can't find what's wrong with it. Your help will be greatly appreciated. Have a nice day, Patryk

0

This is a filter in WordPress called wpautop it is there to make formatting cleaner when publising posts, however when you want more control over formatting it can be a pain. It basically wraps returns in paragraphs so that the space you see in the editor is obeyed on the front end.

You can disable it completely by placing this in your functions.php

remove_filter( 'the_content', 'wpautop' );

Or you can disable it for only elements wrapped in a shortcode by placing this in your functions.php which will delay the formatting until after shortcodes are rendered. This is what the 12 means in the add_filter call - it basically says do this as your 12th process as shortcodes may be executed at the 6th process for example

remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 12);

You can read more about the auto formatting at the codex here: http://codex.wordpress.org/Function_Reference/wpautop

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.